xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 581cede61ac9c14d8d4ea452562a567189eead78)
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_lowater = tcp->tcp_recv_lowater;
5599 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5600 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5601 	eager->tcp_oobinline = tcp->tcp_oobinline;
5602 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5603 	eager->tcp_broadcast = tcp->tcp_broadcast;
5604 	eager->tcp_useloopback = tcp->tcp_useloopback;
5605 	eager->tcp_dontroute = tcp->tcp_dontroute;
5606 	eager->tcp_debug = tcp->tcp_debug;
5607 	eager->tcp_linger = tcp->tcp_linger;
5608 	eager->tcp_lingertime = tcp->tcp_lingertime;
5609 	if (tcp->tcp_ka_enabled)
5610 		eager->tcp_ka_enabled = 1;
5611 
5612 	ASSERT(eager->tcp_recv_hiwater != 0 &&
5613 	    eager->tcp_recv_hiwater == eager->tcp_rwnd);
5614 
5615 	/* Set the IP options */
5616 	econnp->conn_broadcast = connp->conn_broadcast;
5617 	econnp->conn_loopback = connp->conn_loopback;
5618 	econnp->conn_dontroute = connp->conn_dontroute;
5619 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5620 
5621 	/* Put a ref on the listener for the eager. */
5622 	CONN_INC_REF(connp);
5623 	mutex_enter(&tcp->tcp_eager_lock);
5624 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5625 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5626 	tcp->tcp_eager_next_q0 = eager;
5627 	eager->tcp_eager_prev_q0 = tcp;
5628 
5629 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5630 	eager->tcp_listener = tcp;
5631 	eager->tcp_saved_listener = tcp;
5632 
5633 	/*
5634 	 * Tag this detached tcp vector for later retrieval
5635 	 * by our listener client in tcp_accept().
5636 	 */
5637 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5638 	tcp->tcp_conn_req_cnt_q0++;
5639 	if (++tcp->tcp_conn_req_seqnum == -1) {
5640 		/*
5641 		 * -1 is "special" and defined in TPI as something
5642 		 * that should never be used in T_CONN_IND
5643 		 */
5644 		++tcp->tcp_conn_req_seqnum;
5645 	}
5646 	mutex_exit(&tcp->tcp_eager_lock);
5647 
5648 	if (tcp->tcp_syn_defense) {
5649 		/* Don't drop the SYN that comes from a good IP source */
5650 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5651 		if (addr_cache != NULL && eager->tcp_remote ==
5652 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5653 			eager->tcp_dontdrop = B_TRUE;
5654 		}
5655 	}
5656 
5657 	/*
5658 	 * We need to insert the eager in its own perimeter but as soon
5659 	 * as we do that, we expose the eager to the classifier and
5660 	 * should not touch any field outside the eager's perimeter.
5661 	 * So do all the work necessary before inserting the eager
5662 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5663 	 * will succeed but undo everything if it fails.
5664 	 */
5665 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5666 	eager->tcp_irs = seg_seq;
5667 	eager->tcp_rack = seg_seq;
5668 	eager->tcp_rnxt = seg_seq + 1;
5669 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5670 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5671 	eager->tcp_state = TCPS_SYN_RCVD;
5672 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5673 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5674 	if (mp1 == NULL) {
5675 		/*
5676 		 * Increment the ref count as we are going to
5677 		 * enqueueing an mp in squeue
5678 		 */
5679 		CONN_INC_REF(econnp);
5680 		goto error;
5681 	}
5682 
5683 	/*
5684 	 * Note that in theory this should use the current pid
5685 	 * so that getpeerucred on the client returns the actual listener
5686 	 * that does accept. But accept() hasn't been called yet. We could use
5687 	 * the pid of the process that did bind/listen on the server.
5688 	 * However, with common usage like inetd() the bind/listen can be done
5689 	 * by a different process than the accept().
5690 	 * Hence we do the simple thing of using the open pid here.
5691 	 * Note that db_credp is set later in tcp_send_data().
5692 	 */
5693 	mblk_setcred(mp1, credp, tcp->tcp_cpid);
5694 	eager->tcp_cpid = tcp->tcp_cpid;
5695 	eager->tcp_open_time = lbolt64;
5696 
5697 	/*
5698 	 * We need to start the rto timer. In normal case, we start
5699 	 * the timer after sending the packet on the wire (or at
5700 	 * least believing that packet was sent by waiting for
5701 	 * CALL_IP_WPUT() to return). Since this is the first packet
5702 	 * being sent on the wire for the eager, our initial tcp_rto
5703 	 * is at least tcp_rexmit_interval_min which is a fairly
5704 	 * large value to allow the algorithm to adjust slowly to large
5705 	 * fluctuations of RTT during first few transmissions.
5706 	 *
5707 	 * Starting the timer first and then sending the packet in this
5708 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5709 	 * is of the order of several 100ms and starting the timer
5710 	 * first and then sending the packet will result in difference
5711 	 * of few micro seconds.
5712 	 *
5713 	 * Without this optimization, we are forced to hold the fanout
5714 	 * lock across the ipcl_bind_insert() and sending the packet
5715 	 * so that we don't race against an incoming packet (maybe RST)
5716 	 * for this eager.
5717 	 *
5718 	 * It is necessary to acquire an extra reference on the eager
5719 	 * at this point and hold it until after tcp_send_data() to
5720 	 * ensure against an eager close race.
5721 	 */
5722 
5723 	CONN_INC_REF(eager->tcp_connp);
5724 
5725 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5726 
5727 	/*
5728 	 * Insert the eager in its own perimeter now. We are ready to deal
5729 	 * with any packets on eager.
5730 	 */
5731 	if (eager->tcp_ipversion == IPV4_VERSION) {
5732 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5733 			goto error;
5734 		}
5735 	} else {
5736 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5737 			goto error;
5738 		}
5739 	}
5740 
5741 	/* mark conn as fully-bound */
5742 	econnp->conn_fully_bound = B_TRUE;
5743 
5744 	/* Send the SYN-ACK */
5745 	tcp_send_data(eager, eager->tcp_wq, mp1);
5746 	CONN_DEC_REF(eager->tcp_connp);
5747 	freemsg(mp);
5748 
5749 	return;
5750 error:
5751 	freemsg(mp1);
5752 	eager->tcp_closemp_used = B_TRUE;
5753 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5754 	mp1 = &eager->tcp_closemp;
5755 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5756 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5757 
5758 	/*
5759 	 * If a connection already exists, send the mp to that connections so
5760 	 * that it can be appropriately dealt with.
5761 	 */
5762 	ipst = tcps->tcps_netstack->netstack_ip;
5763 
5764 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5765 		if (!IPCL_IS_CONNECTED(econnp)) {
5766 			/*
5767 			 * Something bad happened. ipcl_conn_insert()
5768 			 * failed because a connection already existed
5769 			 * in connected hash but we can't find it
5770 			 * anymore (someone blew it away). Just
5771 			 * free this message and hopefully remote
5772 			 * will retransmit at which time the SYN can be
5773 			 * treated as a new connection or dealth with
5774 			 * a TH_RST if a connection already exists.
5775 			 */
5776 			CONN_DEC_REF(econnp);
5777 			freemsg(mp);
5778 		} else {
5779 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5780 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5781 		}
5782 	} else {
5783 		/* Nobody wants this packet */
5784 		freemsg(mp);
5785 	}
5786 	return;
5787 error3:
5788 	CONN_DEC_REF(econnp);
5789 error2:
5790 	freemsg(mp);
5791 }
5792 
5793 /*
5794  * In an ideal case of vertical partition in NUMA architecture, its
5795  * beneficial to have the listener and all the incoming connections
5796  * tied to the same squeue. The other constraint is that incoming
5797  * connections should be tied to the squeue attached to interrupted
5798  * CPU for obvious locality reason so this leaves the listener to
5799  * be tied to the same squeue. Our only problem is that when listener
5800  * is binding, the CPU that will get interrupted by the NIC whose
5801  * IP address the listener is binding to is not even known. So
5802  * the code below allows us to change that binding at the time the
5803  * CPU is interrupted by virtue of incoming connection's squeue.
5804  *
5805  * This is usefull only in case of a listener bound to a specific IP
5806  * address. For other kind of listeners, they get bound the
5807  * very first time and there is no attempt to rebind them.
5808  */
5809 void
5810 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5811 {
5812 	conn_t		*connp = (conn_t *)arg;
5813 	squeue_t	*sqp = (squeue_t *)arg2;
5814 	squeue_t	*new_sqp;
5815 	uint32_t	conn_flags;
5816 
5817 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5818 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5819 	} else {
5820 		goto done;
5821 	}
5822 
5823 	if (connp->conn_fanout == NULL)
5824 		goto done;
5825 
5826 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5827 		mutex_enter(&connp->conn_fanout->connf_lock);
5828 		mutex_enter(&connp->conn_lock);
5829 		/*
5830 		 * No one from read or write side can access us now
5831 		 * except for already queued packets on this squeue.
5832 		 * But since we haven't changed the squeue yet, they
5833 		 * can't execute. If they are processed after we have
5834 		 * changed the squeue, they are sent back to the
5835 		 * correct squeue down below.
5836 		 * But a listner close can race with processing of
5837 		 * incoming SYN. If incoming SYN processing changes
5838 		 * the squeue then the listener close which is waiting
5839 		 * to enter the squeue would operate on the wrong
5840 		 * squeue. Hence we don't change the squeue here unless
5841 		 * the refcount is exactly the minimum refcount. The
5842 		 * minimum refcount of 4 is counted as - 1 each for
5843 		 * TCP and IP, 1 for being in the classifier hash, and
5844 		 * 1 for the mblk being processed.
5845 		 */
5846 
5847 		if (connp->conn_ref != 4 ||
5848 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5849 			mutex_exit(&connp->conn_lock);
5850 			mutex_exit(&connp->conn_fanout->connf_lock);
5851 			goto done;
5852 		}
5853 		if (connp->conn_sqp != new_sqp) {
5854 			while (connp->conn_sqp != new_sqp)
5855 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5856 		}
5857 
5858 		do {
5859 			conn_flags = connp->conn_flags;
5860 			conn_flags |= IPCL_FULLY_BOUND;
5861 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5862 			    conn_flags);
5863 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5864 
5865 		mutex_exit(&connp->conn_fanout->connf_lock);
5866 		mutex_exit(&connp->conn_lock);
5867 	}
5868 
5869 done:
5870 	if (connp->conn_sqp != sqp) {
5871 		CONN_INC_REF(connp);
5872 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5873 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5874 	} else {
5875 		tcp_conn_request(connp, mp, sqp);
5876 	}
5877 }
5878 
5879 /*
5880  * Successful connect request processing begins when our client passes
5881  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5882  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5883  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5884  *   upstream <- tcp_rput()		<- IP
5885  * After various error checks are completed, tcp_tpi_connect() lays
5886  * the target address and port into the composite header template,
5887  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5888  * request followed by an IRE request, and passes the three mblk message
5889  * down to IP looking like this:
5890  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5891  * Processing continues in tcp_rput() when we receive the following message:
5892  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5893  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5894  * to fire off the connection request, and then passes the T_OK_ACK mblk
5895  * upstream that we filled in below.  There are, of course, numerous
5896  * error conditions along the way which truncate the processing described
5897  * above.
5898  */
5899 static void
5900 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5901 {
5902 	sin_t		*sin;
5903 	queue_t		*q = tcp->tcp_wq;
5904 	struct T_conn_req	*tcr;
5905 	struct sockaddr	*sa;
5906 	socklen_t	len;
5907 	int		error;
5908 	cred_t		*cr;
5909 	pid_t		cpid;
5910 
5911 	/*
5912 	 * All Solaris components should pass a db_credp
5913 	 * for this TPI message, hence we ASSERT.
5914 	 * But in case there is some other M_PROTO that looks
5915 	 * like a TPI message sent by some other kernel
5916 	 * component, we check and return an error.
5917 	 */
5918 	cr = msg_getcred(mp, &cpid);
5919 	ASSERT(cr != NULL);
5920 	if (cr == NULL) {
5921 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5922 		return;
5923 	}
5924 
5925 	tcr = (struct T_conn_req *)mp->b_rptr;
5926 
5927 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5928 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5929 		tcp_err_ack(tcp, mp, TPROTO, 0);
5930 		return;
5931 	}
5932 
5933 	/*
5934 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5935 	 * will always have that to send up.  Otherwise, we need to do
5936 	 * special handling in case the allocation fails at that time.
5937 	 * If the end point is TPI, the tcp_t can be reused and the
5938 	 * tcp_ordrel_mp may be allocated already.
5939 	 */
5940 	if (tcp->tcp_ordrel_mp == NULL) {
5941 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5942 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5943 			return;
5944 		}
5945 	}
5946 
5947 	/*
5948 	 * Determine packet type based on type of address passed in
5949 	 * the request should contain an IPv4 or IPv6 address.
5950 	 * Make sure that address family matches the type of
5951 	 * family of the the address passed down
5952 	 */
5953 	switch (tcr->DEST_length) {
5954 	default:
5955 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5956 		return;
5957 
5958 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5959 		/*
5960 		 * XXX: The check for valid DEST_length was not there
5961 		 * in earlier releases and some buggy
5962 		 * TLI apps (e.g Sybase) got away with not feeding
5963 		 * in sin_zero part of address.
5964 		 * We allow that bug to keep those buggy apps humming.
5965 		 * Test suites require the check on DEST_length.
5966 		 * We construct a new mblk with valid DEST_length
5967 		 * free the original so the rest of the code does
5968 		 * not have to keep track of this special shorter
5969 		 * length address case.
5970 		 */
5971 		mblk_t *nmp;
5972 		struct T_conn_req *ntcr;
5973 		sin_t *nsin;
5974 
5975 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5976 		    tcr->OPT_length, BPRI_HI);
5977 		if (nmp == NULL) {
5978 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5979 			return;
5980 		}
5981 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5982 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5983 		ntcr->PRIM_type = T_CONN_REQ;
5984 		ntcr->DEST_length = sizeof (sin_t);
5985 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5986 
5987 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5988 		*nsin = sin_null;
5989 		/* Get pointer to shorter address to copy from original mp */
5990 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5991 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5992 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5993 			freemsg(nmp);
5994 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5995 			return;
5996 		}
5997 		nsin->sin_family = sin->sin_family;
5998 		nsin->sin_port = sin->sin_port;
5999 		nsin->sin_addr = sin->sin_addr;
6000 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6001 		nmp->b_wptr = (uchar_t *)&nsin[1];
6002 		if (tcr->OPT_length != 0) {
6003 			ntcr->OPT_length = tcr->OPT_length;
6004 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6005 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6006 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6007 			    tcr->OPT_length);
6008 			nmp->b_wptr += tcr->OPT_length;
6009 		}
6010 		freemsg(mp);	/* original mp freed */
6011 		mp = nmp;	/* re-initialize original variables */
6012 		tcr = ntcr;
6013 	}
6014 	/* FALLTHRU */
6015 
6016 	case sizeof (sin_t):
6017 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6018 		    sizeof (sin_t));
6019 		len = sizeof (sin_t);
6020 		break;
6021 
6022 	case sizeof (sin6_t):
6023 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6024 		    sizeof (sin6_t));
6025 		len = sizeof (sin6_t);
6026 		break;
6027 	}
6028 
6029 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6030 	if (error != 0) {
6031 		tcp_err_ack(tcp, mp, TSYSERR, error);
6032 		return;
6033 	}
6034 
6035 	/*
6036 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6037 	 * should key on their sequence number and cut them loose.
6038 	 */
6039 
6040 	/*
6041 	 * If options passed in, feed it for verification and handling
6042 	 */
6043 	if (tcr->OPT_length != 0) {
6044 		mblk_t	*ok_mp;
6045 		mblk_t	*discon_mp;
6046 		mblk_t  *conn_opts_mp;
6047 		int t_error, sys_error, do_disconnect;
6048 
6049 		conn_opts_mp = NULL;
6050 
6051 		if (tcp_conprim_opt_process(tcp, mp,
6052 		    &do_disconnect, &t_error, &sys_error) < 0) {
6053 			if (do_disconnect) {
6054 				ASSERT(t_error == 0 && sys_error == 0);
6055 				discon_mp = mi_tpi_discon_ind(NULL,
6056 				    ECONNREFUSED, 0);
6057 				if (!discon_mp) {
6058 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6059 					    TSYSERR, ENOMEM);
6060 					return;
6061 				}
6062 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6063 				if (!ok_mp) {
6064 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6065 					    TSYSERR, ENOMEM);
6066 					return;
6067 				}
6068 				qreply(q, ok_mp);
6069 				qreply(q, discon_mp); /* no flush! */
6070 			} else {
6071 				ASSERT(t_error != 0);
6072 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6073 				    sys_error);
6074 			}
6075 			return;
6076 		}
6077 		/*
6078 		 * Success in setting options, the mp option buffer represented
6079 		 * by OPT_length/offset has been potentially modified and
6080 		 * contains results of option processing. We copy it in
6081 		 * another mp to save it for potentially influencing returning
6082 		 * it in T_CONN_CONN.
6083 		 */
6084 		if (tcr->OPT_length != 0) { /* there are resulting options */
6085 			conn_opts_mp = copyb(mp);
6086 			if (!conn_opts_mp) {
6087 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6088 				    TSYSERR, ENOMEM);
6089 				return;
6090 			}
6091 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6092 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6093 			/*
6094 			 * Note:
6095 			 * These resulting option negotiation can include any
6096 			 * end-to-end negotiation options but there no such
6097 			 * thing (yet?) in our TCP/IP.
6098 			 */
6099 		}
6100 	}
6101 
6102 	/* call the non-TPI version */
6103 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
6104 	if (error < 0) {
6105 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6106 	} else if (error > 0) {
6107 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6108 	} else {
6109 		mp = mi_tpi_ok_ack_alloc(mp);
6110 	}
6111 
6112 	/*
6113 	 * Note: Code below is the "failure" case
6114 	 */
6115 	/* return error ack and blow away saved option results if any */
6116 connect_failed:
6117 	if (mp != NULL)
6118 		putnext(tcp->tcp_rq, mp);
6119 	else {
6120 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6121 		    TSYSERR, ENOMEM);
6122 	}
6123 }
6124 
6125 /*
6126  * Handle connect to IPv4 destinations, including connections for AF_INET6
6127  * sockets connecting to IPv4 mapped IPv6 destinations.
6128  */
6129 static int
6130 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6131     uint_t srcid, cred_t *cr, pid_t pid)
6132 {
6133 	tcph_t	*tcph;
6134 	mblk_t	*mp;
6135 	ipaddr_t dstaddr = *dstaddrp;
6136 	int32_t	oldstate;
6137 	uint16_t lport;
6138 	int	error = 0;
6139 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6140 
6141 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6142 
6143 	/* Check for attempt to connect to INADDR_ANY */
6144 	if (dstaddr == INADDR_ANY)  {
6145 		/*
6146 		 * SunOS 4.x and 4.3 BSD allow an application
6147 		 * to connect a TCP socket to INADDR_ANY.
6148 		 * When they do this, the kernel picks the
6149 		 * address of one interface and uses it
6150 		 * instead.  The kernel usually ends up
6151 		 * picking the address of the loopback
6152 		 * interface.  This is an undocumented feature.
6153 		 * However, we provide the same thing here
6154 		 * in order to have source and binary
6155 		 * compatibility with SunOS 4.x.
6156 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6157 		 * generate the T_CONN_CON.
6158 		 */
6159 		dstaddr = htonl(INADDR_LOOPBACK);
6160 		*dstaddrp = dstaddr;
6161 	}
6162 
6163 	/* Handle __sin6_src_id if socket not bound to an IP address */
6164 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6165 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6166 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6167 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6168 		    tcp->tcp_ipha->ipha_src);
6169 	}
6170 
6171 	/*
6172 	 * Don't let an endpoint connect to itself.  Note that
6173 	 * the test here does not catch the case where the
6174 	 * source IP addr was left unspecified by the user. In
6175 	 * this case, the source addr is set in tcp_adapt_ire()
6176 	 * using the reply to the T_BIND message that we send
6177 	 * down to IP here and the check is repeated in tcp_rput_other.
6178 	 */
6179 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6180 	    dstport == tcp->tcp_lport) {
6181 		error = -TBADADDR;
6182 		goto failed;
6183 	}
6184 
6185 	/*
6186 	 * Verify the destination is allowed to receive packets
6187 	 * at the security label of the connection we are initiating.
6188 	 * tsol_check_dest() may create a new effective cred for this
6189 	 * connection with a modified label or label flags.
6190 	 */
6191 	if (is_system_labeled()) {
6192 		ASSERT(tcp->tcp_connp->conn_effective_cred == NULL);
6193 		if ((error = tsol_check_dest(CONN_CRED(tcp->tcp_connp),
6194 		    &dstaddr, IPV4_VERSION, tcp->tcp_connp->conn_mac_exempt,
6195 		    &tcp->tcp_connp->conn_effective_cred)) != 0) {
6196 			if (error != EHOSTUNREACH)
6197 				error = -TSYSERR;
6198 			goto failed;
6199 		}
6200 	}
6201 
6202 	tcp->tcp_ipha->ipha_dst = dstaddr;
6203 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6204 
6205 	/*
6206 	 * Massage a source route if any putting the first hop
6207 	 * in iph_dst. Compute a starting value for the checksum which
6208 	 * takes into account that the original iph_dst should be
6209 	 * included in the checksum but that ip will include the
6210 	 * first hop in the source route in the tcp checksum.
6211 	 */
6212 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6213 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6214 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6215 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6216 	if ((int)tcp->tcp_sum < 0)
6217 		tcp->tcp_sum--;
6218 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6219 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6220 	    (tcp->tcp_sum >> 16));
6221 	tcph = tcp->tcp_tcph;
6222 	*(uint16_t *)tcph->th_fport = dstport;
6223 	tcp->tcp_fport = dstport;
6224 
6225 	oldstate = tcp->tcp_state;
6226 	/*
6227 	 * At this point the remote destination address and remote port fields
6228 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6229 	 * have to see which state tcp was in so we can take apropriate action.
6230 	 */
6231 	if (oldstate == TCPS_IDLE) {
6232 		/*
6233 		 * We support a quick connect capability here, allowing
6234 		 * clients to transition directly from IDLE to SYN_SENT
6235 		 * tcp_bindi will pick an unused port, insert the connection
6236 		 * in the bind hash and transition to BOUND state.
6237 		 */
6238 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6239 		    tcp, B_TRUE);
6240 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6241 		    B_FALSE, B_FALSE);
6242 		if (lport == 0) {
6243 			error = -TNOADDR;
6244 			goto failed;
6245 		}
6246 	}
6247 	tcp->tcp_state = TCPS_SYN_SENT;
6248 
6249 	mp = allocb(sizeof (ire_t), BPRI_HI);
6250 	if (mp == NULL) {
6251 		tcp->tcp_state = oldstate;
6252 		error = ENOMEM;
6253 		goto failed;
6254 	}
6255 
6256 	mp->b_wptr += sizeof (ire_t);
6257 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6258 	tcp->tcp_hard_binding = 1;
6259 
6260 	/*
6261 	 * We need to make sure that the conn_recv is set to a non-null
6262 	 * value before we insert the conn_t into the classifier table.
6263 	 * This is to avoid a race with an incoming packet which does
6264 	 * an ipcl_classify().
6265 	 */
6266 	tcp->tcp_connp->conn_recv = tcp_input;
6267 
6268 	if (tcp->tcp_family == AF_INET) {
6269 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6270 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6271 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6272 	} else {
6273 		in6_addr_t v6src;
6274 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6275 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6276 		} else {
6277 			v6src = tcp->tcp_ip6h->ip6_src;
6278 		}
6279 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6280 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6281 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6282 	}
6283 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6284 	tcp->tcp_active_open = 1;
6285 
6286 
6287 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6288 failed:
6289 	/* return error ack and blow away saved option results if any */
6290 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6291 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6292 	return (error);
6293 }
6294 
6295 /*
6296  * Handle connect to IPv6 destinations.
6297  */
6298 static int
6299 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6300     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6301 {
6302 	tcph_t	*tcph;
6303 	mblk_t	*mp;
6304 	ip6_rthdr_t *rth;
6305 	int32_t  oldstate;
6306 	uint16_t lport;
6307 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6308 	int	error = 0;
6309 	conn_t	*connp = tcp->tcp_connp;
6310 
6311 	ASSERT(tcp->tcp_family == AF_INET6);
6312 
6313 	/*
6314 	 * If we're here, it means that the destination address is a native
6315 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6316 	 * reason why it might not be IPv6 is if the socket was bound to an
6317 	 * IPv4-mapped IPv6 address.
6318 	 */
6319 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6320 		return (-TBADADDR);
6321 	}
6322 
6323 	/*
6324 	 * Interpret a zero destination to mean loopback.
6325 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6326 	 * generate the T_CONN_CON.
6327 	 */
6328 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6329 		*dstaddrp = ipv6_loopback;
6330 	}
6331 
6332 	/* Handle __sin6_src_id if socket not bound to an IP address */
6333 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6334 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6335 		    connp->conn_zoneid, tcps->tcps_netstack);
6336 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6337 	}
6338 
6339 	/*
6340 	 * Take care of the scope_id now and add ip6i_t
6341 	 * if ip6i_t is not already allocated through TCP
6342 	 * sticky options. At this point tcp_ip6h does not
6343 	 * have dst info, thus use dstaddrp.
6344 	 */
6345 	if (scope_id != 0 &&
6346 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6347 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6348 		ip6i_t  *ip6i;
6349 
6350 		ipp->ipp_ifindex = scope_id;
6351 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6352 
6353 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6354 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6355 			/* Already allocated */
6356 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6357 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6358 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6359 		} else {
6360 			int reterr;
6361 
6362 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6363 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6364 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6365 			reterr = tcp_build_hdrs(tcp);
6366 			if (reterr != 0)
6367 				goto failed;
6368 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6369 		}
6370 	}
6371 
6372 	/*
6373 	 * Don't let an endpoint connect to itself.  Note that
6374 	 * the test here does not catch the case where the
6375 	 * source IP addr was left unspecified by the user. In
6376 	 * this case, the source addr is set in tcp_adapt_ire()
6377 	 * using the reply to the T_BIND message that we send
6378 	 * down to IP here and the check is repeated in tcp_rput_other.
6379 	 */
6380 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6381 	    (dstport == tcp->tcp_lport)) {
6382 		error = -TBADADDR;
6383 		goto failed;
6384 	}
6385 
6386 	/*
6387 	 * Verify the destination is allowed to receive packets
6388 	 * at the security label of the connection we are initiating.
6389 	 * check_dest may create a new effective cred for this
6390 	 * connection with a modified label or label flags.
6391 	 */
6392 	if (is_system_labeled()) {
6393 		ASSERT(tcp->tcp_connp->conn_effective_cred == NULL);
6394 		if ((error = tsol_check_dest(CONN_CRED(tcp->tcp_connp),
6395 		    dstaddrp, IPV6_VERSION, tcp->tcp_connp->conn_mac_exempt,
6396 		    &tcp->tcp_connp->conn_effective_cred)) != 0) {
6397 			if (error != EHOSTUNREACH)
6398 				error = -TSYSERR;
6399 			goto failed;
6400 		}
6401 	}
6402 
6403 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6404 	tcp->tcp_remote_v6 = *dstaddrp;
6405 	tcp->tcp_ip6h->ip6_vcf =
6406 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6407 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6408 
6409 	/*
6410 	 * Massage a routing header (if present) putting the first hop
6411 	 * in ip6_dst. Compute a starting value for the checksum which
6412 	 * takes into account that the original ip6_dst should be
6413 	 * included in the checksum but that ip will include the
6414 	 * first hop in the source route in the tcp checksum.
6415 	 */
6416 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6417 	if (rth != NULL) {
6418 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6419 		    tcps->tcps_netstack);
6420 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6421 		    (tcp->tcp_sum >> 16));
6422 	} else {
6423 		tcp->tcp_sum = 0;
6424 	}
6425 
6426 	tcph = tcp->tcp_tcph;
6427 	*(uint16_t *)tcph->th_fport = dstport;
6428 	tcp->tcp_fport = dstport;
6429 
6430 	oldstate = tcp->tcp_state;
6431 	/*
6432 	 * At this point the remote destination address and remote port fields
6433 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6434 	 * have to see which state tcp was in so we can take apropriate action.
6435 	 */
6436 	if (oldstate == TCPS_IDLE) {
6437 		/*
6438 		 * We support a quick connect capability here, allowing
6439 		 * clients to transition directly from IDLE to SYN_SENT
6440 		 * tcp_bindi will pick an unused port, insert the connection
6441 		 * in the bind hash and transition to BOUND state.
6442 		 */
6443 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6444 		    tcp, B_TRUE);
6445 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6446 		    B_FALSE, B_FALSE);
6447 		if (lport == 0) {
6448 			error = -TNOADDR;
6449 			goto failed;
6450 		}
6451 	}
6452 	tcp->tcp_state = TCPS_SYN_SENT;
6453 
6454 	mp = allocb(sizeof (ire_t), BPRI_HI);
6455 	if (mp != NULL) {
6456 		in6_addr_t v6src;
6457 
6458 		mp->b_wptr += sizeof (ire_t);
6459 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6460 
6461 		tcp->tcp_hard_binding = 1;
6462 
6463 		/*
6464 		 * We need to make sure that the conn_recv is set to a non-null
6465 		 * value before we insert the conn_t into the classifier table.
6466 		 * This is to avoid a race with an incoming packet which does
6467 		 * an ipcl_classify().
6468 		 */
6469 		tcp->tcp_connp->conn_recv = tcp_input;
6470 
6471 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6472 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6473 		} else {
6474 			v6src = tcp->tcp_ip6h->ip6_src;
6475 		}
6476 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6477 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6478 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6479 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6480 		tcp->tcp_active_open = 1;
6481 
6482 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6483 	}
6484 	/* Error case */
6485 	tcp->tcp_state = oldstate;
6486 	error = ENOMEM;
6487 
6488 failed:
6489 	/* return error ack and blow away saved option results if any */
6490 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6491 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6492 	return (error);
6493 }
6494 
6495 /*
6496  * We need a stream q for detached closing tcp connections
6497  * to use.  Our client hereby indicates that this q is the
6498  * one to use.
6499  */
6500 static void
6501 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6502 {
6503 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6504 	queue_t	*q = tcp->tcp_wq;
6505 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6506 
6507 #ifdef NS_DEBUG
6508 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6509 	    tcps->tcps_netstack->netstack_stackid);
6510 #endif
6511 	mp->b_datap->db_type = M_IOCACK;
6512 	iocp->ioc_count = 0;
6513 	mutex_enter(&tcps->tcps_g_q_lock);
6514 	if (tcps->tcps_g_q != NULL) {
6515 		mutex_exit(&tcps->tcps_g_q_lock);
6516 		iocp->ioc_error = EALREADY;
6517 	} else {
6518 		int error = 0;
6519 		conn_t *connp = tcp->tcp_connp;
6520 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6521 
6522 		tcps->tcps_g_q = tcp->tcp_rq;
6523 		mutex_exit(&tcps->tcps_g_q_lock);
6524 		iocp->ioc_error = 0;
6525 		iocp->ioc_rval = 0;
6526 		/*
6527 		 * We are passing tcp_sticky_ipp as NULL
6528 		 * as it is not useful for tcp_default queue
6529 		 *
6530 		 * Set conn_recv just in case.
6531 		 */
6532 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6533 
6534 		ASSERT(connp->conn_af_isv6);
6535 		connp->conn_ulp = IPPROTO_TCP;
6536 
6537 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6538 		    NULL || connp->conn_mac_exempt) {
6539 			error = -TBADADDR;
6540 		} else {
6541 			connp->conn_srcv6 = ipv6_all_zeros;
6542 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6543 		}
6544 
6545 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6546 	}
6547 	qreply(q, mp);
6548 }
6549 
6550 static int
6551 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6552 {
6553 	tcp_t	*ltcp = NULL;
6554 	conn_t	*connp;
6555 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6556 
6557 	/*
6558 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6559 	 * when the stream is in BOUND state. Do not send a reset,
6560 	 * since the destination IP address is not valid, and it can
6561 	 * be the initialized value of all zeros (broadcast address).
6562 	 *
6563 	 * XXX There won't be any pending bind request to IP.
6564 	 */
6565 	if (tcp->tcp_state <= TCPS_BOUND) {
6566 		if (tcp->tcp_debug) {
6567 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6568 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6569 		}
6570 		return (TOUTSTATE);
6571 	}
6572 
6573 
6574 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6575 
6576 		/*
6577 		 * According to TPI, for non-listeners, ignore seqnum
6578 		 * and disconnect.
6579 		 * Following interpretation of -1 seqnum is historical
6580 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6581 		 * a valid seqnum should not be -1).
6582 		 *
6583 		 *	-1 means disconnect everything
6584 		 *	regardless even on a listener.
6585 		 */
6586 
6587 		int old_state = tcp->tcp_state;
6588 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6589 
6590 		/*
6591 		 * The connection can't be on the tcp_time_wait_head list
6592 		 * since it is not detached.
6593 		 */
6594 		ASSERT(tcp->tcp_time_wait_next == NULL);
6595 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6596 		ASSERT(tcp->tcp_time_wait_expire == 0);
6597 		ltcp = NULL;
6598 		/*
6599 		 * If it used to be a listener, check to make sure no one else
6600 		 * has taken the port before switching back to LISTEN state.
6601 		 */
6602 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6603 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6604 			    tcp->tcp_ipha->ipha_src,
6605 			    tcp->tcp_connp->conn_zoneid, ipst);
6606 			if (connp != NULL)
6607 				ltcp = connp->conn_tcp;
6608 		} else {
6609 			/* Allow tcp_bound_if listeners? */
6610 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6611 			    &tcp->tcp_ip6h->ip6_src, 0,
6612 			    tcp->tcp_connp->conn_zoneid, ipst);
6613 			if (connp != NULL)
6614 				ltcp = connp->conn_tcp;
6615 		}
6616 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6617 			tcp->tcp_state = TCPS_LISTEN;
6618 		} else if (old_state > TCPS_BOUND) {
6619 			tcp->tcp_conn_req_max = 0;
6620 			tcp->tcp_state = TCPS_BOUND;
6621 		}
6622 		if (ltcp != NULL)
6623 			CONN_DEC_REF(ltcp->tcp_connp);
6624 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6625 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6626 		} else if (old_state == TCPS_ESTABLISHED ||
6627 		    old_state == TCPS_CLOSE_WAIT) {
6628 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6629 		}
6630 
6631 		if (tcp->tcp_fused)
6632 			tcp_unfuse(tcp);
6633 
6634 		mutex_enter(&tcp->tcp_eager_lock);
6635 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6636 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6637 			tcp_eager_cleanup(tcp, 0);
6638 		}
6639 		mutex_exit(&tcp->tcp_eager_lock);
6640 
6641 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6642 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6643 
6644 		tcp_reinit(tcp);
6645 
6646 		return (0);
6647 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6648 		return (TBADSEQ);
6649 	}
6650 	return (0);
6651 }
6652 
6653 /*
6654  * Our client hereby directs us to reject the connection request
6655  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6656  * of sending the appropriate RST, not an ICMP error.
6657  */
6658 static void
6659 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6660 {
6661 	t_scalar_t seqnum;
6662 	int	error;
6663 
6664 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6665 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6666 		tcp_err_ack(tcp, mp, TPROTO, 0);
6667 		return;
6668 	}
6669 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6670 	error = tcp_disconnect_common(tcp, seqnum);
6671 	if (error != 0)
6672 		tcp_err_ack(tcp, mp, error, 0);
6673 	else {
6674 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6675 			/* Send M_FLUSH according to TPI */
6676 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6677 		}
6678 		mp = mi_tpi_ok_ack_alloc(mp);
6679 		if (mp)
6680 			putnext(tcp->tcp_rq, mp);
6681 	}
6682 }
6683 
6684 /*
6685  * Diagnostic routine used to return a string associated with the tcp state.
6686  * Note that if the caller does not supply a buffer, it will use an internal
6687  * static string.  This means that if multiple threads call this function at
6688  * the same time, output can be corrupted...  Note also that this function
6689  * does not check the size of the supplied buffer.  The caller has to make
6690  * sure that it is big enough.
6691  */
6692 static char *
6693 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6694 {
6695 	char		buf1[30];
6696 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6697 	char		*buf;
6698 	char		*cp;
6699 	in6_addr_t	local, remote;
6700 	char		local_addrbuf[INET6_ADDRSTRLEN];
6701 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6702 
6703 	if (sup_buf != NULL)
6704 		buf = sup_buf;
6705 	else
6706 		buf = priv_buf;
6707 
6708 	if (tcp == NULL)
6709 		return ("NULL_TCP");
6710 	switch (tcp->tcp_state) {
6711 	case TCPS_CLOSED:
6712 		cp = "TCP_CLOSED";
6713 		break;
6714 	case TCPS_IDLE:
6715 		cp = "TCP_IDLE";
6716 		break;
6717 	case TCPS_BOUND:
6718 		cp = "TCP_BOUND";
6719 		break;
6720 	case TCPS_LISTEN:
6721 		cp = "TCP_LISTEN";
6722 		break;
6723 	case TCPS_SYN_SENT:
6724 		cp = "TCP_SYN_SENT";
6725 		break;
6726 	case TCPS_SYN_RCVD:
6727 		cp = "TCP_SYN_RCVD";
6728 		break;
6729 	case TCPS_ESTABLISHED:
6730 		cp = "TCP_ESTABLISHED";
6731 		break;
6732 	case TCPS_CLOSE_WAIT:
6733 		cp = "TCP_CLOSE_WAIT";
6734 		break;
6735 	case TCPS_FIN_WAIT_1:
6736 		cp = "TCP_FIN_WAIT_1";
6737 		break;
6738 	case TCPS_CLOSING:
6739 		cp = "TCP_CLOSING";
6740 		break;
6741 	case TCPS_LAST_ACK:
6742 		cp = "TCP_LAST_ACK";
6743 		break;
6744 	case TCPS_FIN_WAIT_2:
6745 		cp = "TCP_FIN_WAIT_2";
6746 		break;
6747 	case TCPS_TIME_WAIT:
6748 		cp = "TCP_TIME_WAIT";
6749 		break;
6750 	default:
6751 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6752 		cp = buf1;
6753 		break;
6754 	}
6755 	switch (format) {
6756 	case DISP_ADDR_AND_PORT:
6757 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6758 			/*
6759 			 * Note that we use the remote address in the tcp_b
6760 			 * structure.  This means that it will print out
6761 			 * the real destination address, not the next hop's
6762 			 * address if source routing is used.
6763 			 */
6764 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6765 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6766 
6767 		} else {
6768 			local = tcp->tcp_ip_src_v6;
6769 			remote = tcp->tcp_remote_v6;
6770 		}
6771 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6772 		    sizeof (local_addrbuf));
6773 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6774 		    sizeof (remote_addrbuf));
6775 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6776 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6777 		    ntohs(tcp->tcp_fport), cp);
6778 		break;
6779 	case DISP_PORT_ONLY:
6780 	default:
6781 		(void) mi_sprintf(buf, "[%u, %u] %s",
6782 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6783 		break;
6784 	}
6785 
6786 	return (buf);
6787 }
6788 
6789 /*
6790  * Called via squeue to get on to eager's perimeter. It sends a
6791  * TH_RST if eager is in the fanout table. The listener wants the
6792  * eager to disappear either by means of tcp_eager_blowoff() or
6793  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6794  * called (via squeue) if the eager cannot be inserted in the
6795  * fanout table in tcp_conn_request().
6796  */
6797 /* ARGSUSED */
6798 void
6799 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6800 {
6801 	conn_t	*econnp = (conn_t *)arg;
6802 	tcp_t	*eager = econnp->conn_tcp;
6803 	tcp_t	*listener = eager->tcp_listener;
6804 	tcp_stack_t	*tcps = eager->tcp_tcps;
6805 
6806 	/*
6807 	 * We could be called because listener is closing. Since
6808 	 * the eager is using listener's queue's, its not safe.
6809 	 * Better use the default queue just to send the TH_RST
6810 	 * out.
6811 	 */
6812 	ASSERT(tcps->tcps_g_q != NULL);
6813 	eager->tcp_rq = tcps->tcps_g_q;
6814 	eager->tcp_wq = WR(tcps->tcps_g_q);
6815 
6816 	/*
6817 	 * An eager's conn_fanout will be NULL if it's a duplicate
6818 	 * for an existing 4-tuples in the conn fanout table.
6819 	 * We don't want to send an RST out in such case.
6820 	 */
6821 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6822 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6823 		    eager, eager->tcp_snxt, 0, TH_RST);
6824 	}
6825 
6826 	/* We are here because listener wants this eager gone */
6827 	if (listener != NULL) {
6828 		mutex_enter(&listener->tcp_eager_lock);
6829 		tcp_eager_unlink(eager);
6830 		if (eager->tcp_tconnind_started) {
6831 			/*
6832 			 * The eager has sent a conn_ind up to the
6833 			 * listener but listener decides to close
6834 			 * instead. We need to drop the extra ref
6835 			 * placed on eager in tcp_rput_data() before
6836 			 * sending the conn_ind to listener.
6837 			 */
6838 			CONN_DEC_REF(econnp);
6839 		}
6840 		mutex_exit(&listener->tcp_eager_lock);
6841 		CONN_DEC_REF(listener->tcp_connp);
6842 	}
6843 
6844 	if (eager->tcp_state != TCPS_CLOSED)
6845 		tcp_close_detached(eager);
6846 }
6847 
6848 /*
6849  * Reset any eager connection hanging off this listener marked
6850  * with 'seqnum' and then reclaim it's resources.
6851  */
6852 static boolean_t
6853 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6854 {
6855 	tcp_t	*eager;
6856 	mblk_t 	*mp;
6857 	tcp_stack_t	*tcps = listener->tcp_tcps;
6858 
6859 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6860 	eager = listener;
6861 	mutex_enter(&listener->tcp_eager_lock);
6862 	do {
6863 		eager = eager->tcp_eager_next_q;
6864 		if (eager == NULL) {
6865 			mutex_exit(&listener->tcp_eager_lock);
6866 			return (B_FALSE);
6867 		}
6868 	} while (eager->tcp_conn_req_seqnum != seqnum);
6869 
6870 	if (eager->tcp_closemp_used) {
6871 		mutex_exit(&listener->tcp_eager_lock);
6872 		return (B_TRUE);
6873 	}
6874 	eager->tcp_closemp_used = B_TRUE;
6875 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6876 	CONN_INC_REF(eager->tcp_connp);
6877 	mutex_exit(&listener->tcp_eager_lock);
6878 	mp = &eager->tcp_closemp;
6879 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6880 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6881 	return (B_TRUE);
6882 }
6883 
6884 /*
6885  * Reset any eager connection hanging off this listener
6886  * and then reclaim it's resources.
6887  */
6888 static void
6889 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6890 {
6891 	tcp_t	*eager;
6892 	mblk_t	*mp;
6893 	tcp_stack_t	*tcps = listener->tcp_tcps;
6894 
6895 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6896 
6897 	if (!q0_only) {
6898 		/* First cleanup q */
6899 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6900 		eager = listener->tcp_eager_next_q;
6901 		while (eager != NULL) {
6902 			if (!eager->tcp_closemp_used) {
6903 				eager->tcp_closemp_used = B_TRUE;
6904 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6905 				CONN_INC_REF(eager->tcp_connp);
6906 				mp = &eager->tcp_closemp;
6907 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6908 				    tcp_eager_kill, eager->tcp_connp,
6909 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6910 			}
6911 			eager = eager->tcp_eager_next_q;
6912 		}
6913 	}
6914 	/* Then cleanup q0 */
6915 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6916 	eager = listener->tcp_eager_next_q0;
6917 	while (eager != listener) {
6918 		if (!eager->tcp_closemp_used) {
6919 			eager->tcp_closemp_used = B_TRUE;
6920 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6921 			CONN_INC_REF(eager->tcp_connp);
6922 			mp = &eager->tcp_closemp;
6923 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6924 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6925 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6926 		}
6927 		eager = eager->tcp_eager_next_q0;
6928 	}
6929 }
6930 
6931 /*
6932  * If we are an eager connection hanging off a listener that hasn't
6933  * formally accepted the connection yet, get off his list and blow off
6934  * any data that we have accumulated.
6935  */
6936 static void
6937 tcp_eager_unlink(tcp_t *tcp)
6938 {
6939 	tcp_t	*listener = tcp->tcp_listener;
6940 
6941 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6942 	ASSERT(listener != NULL);
6943 	if (tcp->tcp_eager_next_q0 != NULL) {
6944 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6945 
6946 		/* Remove the eager tcp from q0 */
6947 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6948 		    tcp->tcp_eager_prev_q0;
6949 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6950 		    tcp->tcp_eager_next_q0;
6951 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6952 		listener->tcp_conn_req_cnt_q0--;
6953 
6954 		tcp->tcp_eager_next_q0 = NULL;
6955 		tcp->tcp_eager_prev_q0 = NULL;
6956 
6957 		/*
6958 		 * Take the eager out, if it is in the list of droppable
6959 		 * eagers.
6960 		 */
6961 		MAKE_UNDROPPABLE(tcp);
6962 
6963 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6964 			/* we have timed out before */
6965 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6966 			listener->tcp_syn_rcvd_timeout--;
6967 		}
6968 	} else {
6969 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6970 		tcp_t	*prev = NULL;
6971 
6972 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6973 			if (tcpp[0] == tcp) {
6974 				if (listener->tcp_eager_last_q == tcp) {
6975 					/*
6976 					 * If we are unlinking the last
6977 					 * element on the list, adjust
6978 					 * tail pointer. Set tail pointer
6979 					 * to nil when list is empty.
6980 					 */
6981 					ASSERT(tcp->tcp_eager_next_q == NULL);
6982 					if (listener->tcp_eager_last_q ==
6983 					    listener->tcp_eager_next_q) {
6984 						listener->tcp_eager_last_q =
6985 						    NULL;
6986 					} else {
6987 						/*
6988 						 * We won't get here if there
6989 						 * is only one eager in the
6990 						 * list.
6991 						 */
6992 						ASSERT(prev != NULL);
6993 						listener->tcp_eager_last_q =
6994 						    prev;
6995 					}
6996 				}
6997 				tcpp[0] = tcp->tcp_eager_next_q;
6998 				tcp->tcp_eager_next_q = NULL;
6999 				tcp->tcp_eager_last_q = NULL;
7000 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7001 				listener->tcp_conn_req_cnt_q--;
7002 				break;
7003 			}
7004 			prev = tcpp[0];
7005 		}
7006 	}
7007 	tcp->tcp_listener = NULL;
7008 }
7009 
7010 /* Shorthand to generate and send TPI error acks to our client */
7011 static void
7012 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7013 {
7014 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7015 		putnext(tcp->tcp_rq, mp);
7016 }
7017 
7018 /* Shorthand to generate and send TPI error acks to our client */
7019 static void
7020 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7021     int t_error, int sys_error)
7022 {
7023 	struct T_error_ack	*teackp;
7024 
7025 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7026 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7027 		teackp = (struct T_error_ack *)mp->b_rptr;
7028 		teackp->ERROR_prim = primitive;
7029 		teackp->TLI_error = t_error;
7030 		teackp->UNIX_error = sys_error;
7031 		putnext(tcp->tcp_rq, mp);
7032 	}
7033 }
7034 
7035 /*
7036  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7037  * but instead the code relies on:
7038  * - the fact that the address of the array and its size never changes
7039  * - the atomic assignment of the elements of the array
7040  */
7041 /* ARGSUSED */
7042 static int
7043 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7044 {
7045 	int i;
7046 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7047 
7048 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7049 		if (tcps->tcps_g_epriv_ports[i] != 0)
7050 			(void) mi_mpprintf(mp, "%d ",
7051 			    tcps->tcps_g_epriv_ports[i]);
7052 	}
7053 	return (0);
7054 }
7055 
7056 /*
7057  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7058  * threads from changing it at the same time.
7059  */
7060 /* ARGSUSED */
7061 static int
7062 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7063     cred_t *cr)
7064 {
7065 	long	new_value;
7066 	int	i;
7067 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7068 
7069 	/*
7070 	 * Fail the request if the new value does not lie within the
7071 	 * port number limits.
7072 	 */
7073 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7074 	    new_value <= 0 || new_value >= 65536) {
7075 		return (EINVAL);
7076 	}
7077 
7078 	mutex_enter(&tcps->tcps_epriv_port_lock);
7079 	/* Check if the value is already in the list */
7080 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7081 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7082 			mutex_exit(&tcps->tcps_epriv_port_lock);
7083 			return (EEXIST);
7084 		}
7085 	}
7086 	/* Find an empty slot */
7087 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7088 		if (tcps->tcps_g_epriv_ports[i] == 0)
7089 			break;
7090 	}
7091 	if (i == tcps->tcps_g_num_epriv_ports) {
7092 		mutex_exit(&tcps->tcps_epriv_port_lock);
7093 		return (EOVERFLOW);
7094 	}
7095 	/* Set the new value */
7096 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7097 	mutex_exit(&tcps->tcps_epriv_port_lock);
7098 	return (0);
7099 }
7100 
7101 /*
7102  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7103  * threads from changing it at the same time.
7104  */
7105 /* ARGSUSED */
7106 static int
7107 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7108     cred_t *cr)
7109 {
7110 	long	new_value;
7111 	int	i;
7112 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7113 
7114 	/*
7115 	 * Fail the request if the new value does not lie within the
7116 	 * port number limits.
7117 	 */
7118 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7119 	    new_value >= 65536) {
7120 		return (EINVAL);
7121 	}
7122 
7123 	mutex_enter(&tcps->tcps_epriv_port_lock);
7124 	/* Check that the value is already in the list */
7125 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7126 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7127 			break;
7128 	}
7129 	if (i == tcps->tcps_g_num_epriv_ports) {
7130 		mutex_exit(&tcps->tcps_epriv_port_lock);
7131 		return (ESRCH);
7132 	}
7133 	/* Clear the value */
7134 	tcps->tcps_g_epriv_ports[i] = 0;
7135 	mutex_exit(&tcps->tcps_epriv_port_lock);
7136 	return (0);
7137 }
7138 
7139 /* Return the TPI/TLI equivalent of our current tcp_state */
7140 static int
7141 tcp_tpistate(tcp_t *tcp)
7142 {
7143 	switch (tcp->tcp_state) {
7144 	case TCPS_IDLE:
7145 		return (TS_UNBND);
7146 	case TCPS_LISTEN:
7147 		/*
7148 		 * Return whether there are outstanding T_CONN_IND waiting
7149 		 * for the matching T_CONN_RES. Therefore don't count q0.
7150 		 */
7151 		if (tcp->tcp_conn_req_cnt_q > 0)
7152 			return (TS_WRES_CIND);
7153 		else
7154 			return (TS_IDLE);
7155 	case TCPS_BOUND:
7156 		return (TS_IDLE);
7157 	case TCPS_SYN_SENT:
7158 		return (TS_WCON_CREQ);
7159 	case TCPS_SYN_RCVD:
7160 		/*
7161 		 * Note: assumption: this has to the active open SYN_RCVD.
7162 		 * The passive instance is detached in SYN_RCVD stage of
7163 		 * incoming connection processing so we cannot get request
7164 		 * for T_info_ack on it.
7165 		 */
7166 		return (TS_WACK_CRES);
7167 	case TCPS_ESTABLISHED:
7168 		return (TS_DATA_XFER);
7169 	case TCPS_CLOSE_WAIT:
7170 		return (TS_WREQ_ORDREL);
7171 	case TCPS_FIN_WAIT_1:
7172 		return (TS_WIND_ORDREL);
7173 	case TCPS_FIN_WAIT_2:
7174 		return (TS_WIND_ORDREL);
7175 
7176 	case TCPS_CLOSING:
7177 	case TCPS_LAST_ACK:
7178 	case TCPS_TIME_WAIT:
7179 	case TCPS_CLOSED:
7180 		/*
7181 		 * Following TS_WACK_DREQ7 is a rendition of "not
7182 		 * yet TS_IDLE" TPI state. There is no best match to any
7183 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7184 		 * choose a value chosen that will map to TLI/XTI level
7185 		 * state of TSTATECHNG (state is process of changing) which
7186 		 * captures what this dummy state represents.
7187 		 */
7188 		return (TS_WACK_DREQ7);
7189 	default:
7190 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7191 		    tcp->tcp_state, tcp_display(tcp, NULL,
7192 		    DISP_PORT_ONLY));
7193 		return (TS_UNBND);
7194 	}
7195 }
7196 
7197 static void
7198 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7199 {
7200 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7201 
7202 	if (tcp->tcp_family == AF_INET6)
7203 		*tia = tcp_g_t_info_ack_v6;
7204 	else
7205 		*tia = tcp_g_t_info_ack;
7206 	tia->CURRENT_state = tcp_tpistate(tcp);
7207 	tia->OPT_size = tcp_max_optsize;
7208 	if (tcp->tcp_mss == 0) {
7209 		/* Not yet set - tcp_open does not set mss */
7210 		if (tcp->tcp_ipversion == IPV4_VERSION)
7211 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7212 		else
7213 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7214 	} else {
7215 		tia->TIDU_size = tcp->tcp_mss;
7216 	}
7217 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7218 }
7219 
7220 static void
7221 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7222     t_uscalar_t cap_bits1)
7223 {
7224 	tcap->CAP_bits1 = 0;
7225 
7226 	if (cap_bits1 & TC1_INFO) {
7227 		tcp_copy_info(&tcap->INFO_ack, tcp);
7228 		tcap->CAP_bits1 |= TC1_INFO;
7229 	}
7230 
7231 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7232 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7233 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7234 	}
7235 
7236 }
7237 
7238 /*
7239  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7240  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7241  * tcp_g_t_info_ack.  The current state of the stream is copied from
7242  * tcp_state.
7243  */
7244 static void
7245 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7246 {
7247 	t_uscalar_t		cap_bits1;
7248 	struct T_capability_ack	*tcap;
7249 
7250 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7251 		freemsg(mp);
7252 		return;
7253 	}
7254 
7255 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7256 
7257 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7258 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7259 	if (mp == NULL)
7260 		return;
7261 
7262 	tcap = (struct T_capability_ack *)mp->b_rptr;
7263 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7264 
7265 	putnext(tcp->tcp_rq, mp);
7266 }
7267 
7268 /*
7269  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7270  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7271  * The current state of the stream is copied from tcp_state.
7272  */
7273 static void
7274 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7275 {
7276 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7277 	    T_INFO_ACK);
7278 	if (!mp) {
7279 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7280 		return;
7281 	}
7282 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7283 	putnext(tcp->tcp_rq, mp);
7284 }
7285 
7286 /* Respond to the TPI addr request */
7287 static void
7288 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7289 {
7290 	sin_t	*sin;
7291 	mblk_t	*ackmp;
7292 	struct T_addr_ack *taa;
7293 
7294 	/* Make it large enough for worst case */
7295 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7296 	    2 * sizeof (sin6_t), 1);
7297 	if (ackmp == NULL) {
7298 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7299 		return;
7300 	}
7301 
7302 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7303 		tcp_addr_req_ipv6(tcp, ackmp);
7304 		return;
7305 	}
7306 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7307 
7308 	bzero(taa, sizeof (struct T_addr_ack));
7309 	ackmp->b_wptr = (uchar_t *)&taa[1];
7310 
7311 	taa->PRIM_type = T_ADDR_ACK;
7312 	ackmp->b_datap->db_type = M_PCPROTO;
7313 
7314 	/*
7315 	 * Note: Following code assumes 32 bit alignment of basic
7316 	 * data structures like sin_t and struct T_addr_ack.
7317 	 */
7318 	if (tcp->tcp_state >= TCPS_BOUND) {
7319 		/*
7320 		 * Fill in local address
7321 		 */
7322 		taa->LOCADDR_length = sizeof (sin_t);
7323 		taa->LOCADDR_offset = sizeof (*taa);
7324 
7325 		sin = (sin_t *)&taa[1];
7326 
7327 		/* Fill zeroes and then intialize non-zero fields */
7328 		*sin = sin_null;
7329 
7330 		sin->sin_family = AF_INET;
7331 
7332 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7333 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7334 
7335 		ackmp->b_wptr = (uchar_t *)&sin[1];
7336 
7337 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7338 			/*
7339 			 * Fill in Remote address
7340 			 */
7341 			taa->REMADDR_length = sizeof (sin_t);
7342 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7343 			    taa->LOCADDR_length);
7344 
7345 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7346 			*sin = sin_null;
7347 			sin->sin_family = AF_INET;
7348 			sin->sin_addr.s_addr = tcp->tcp_remote;
7349 			sin->sin_port = tcp->tcp_fport;
7350 
7351 			ackmp->b_wptr = (uchar_t *)&sin[1];
7352 		}
7353 	}
7354 	putnext(tcp->tcp_rq, ackmp);
7355 }
7356 
7357 /* Assumes that tcp_addr_req gets enough space and alignment */
7358 static void
7359 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7360 {
7361 	sin6_t	*sin6;
7362 	struct T_addr_ack *taa;
7363 
7364 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7365 	ASSERT(OK_32PTR(ackmp->b_rptr));
7366 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7367 	    2 * sizeof (sin6_t));
7368 
7369 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7370 
7371 	bzero(taa, sizeof (struct T_addr_ack));
7372 	ackmp->b_wptr = (uchar_t *)&taa[1];
7373 
7374 	taa->PRIM_type = T_ADDR_ACK;
7375 	ackmp->b_datap->db_type = M_PCPROTO;
7376 
7377 	/*
7378 	 * Note: Following code assumes 32 bit alignment of basic
7379 	 * data structures like sin6_t and struct T_addr_ack.
7380 	 */
7381 	if (tcp->tcp_state >= TCPS_BOUND) {
7382 		/*
7383 		 * Fill in local address
7384 		 */
7385 		taa->LOCADDR_length = sizeof (sin6_t);
7386 		taa->LOCADDR_offset = sizeof (*taa);
7387 
7388 		sin6 = (sin6_t *)&taa[1];
7389 		*sin6 = sin6_null;
7390 
7391 		sin6->sin6_family = AF_INET6;
7392 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7393 		sin6->sin6_port = tcp->tcp_lport;
7394 
7395 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7396 
7397 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7398 			/*
7399 			 * Fill in Remote address
7400 			 */
7401 			taa->REMADDR_length = sizeof (sin6_t);
7402 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7403 			    taa->LOCADDR_length);
7404 
7405 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7406 			*sin6 = sin6_null;
7407 			sin6->sin6_family = AF_INET6;
7408 			sin6->sin6_flowinfo =
7409 			    tcp->tcp_ip6h->ip6_vcf &
7410 			    ~IPV6_VERS_AND_FLOW_MASK;
7411 			sin6->sin6_addr = tcp->tcp_remote_v6;
7412 			sin6->sin6_port = tcp->tcp_fport;
7413 
7414 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7415 		}
7416 	}
7417 	putnext(tcp->tcp_rq, ackmp);
7418 }
7419 
7420 /*
7421  * Handle reinitialization of a tcp structure.
7422  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7423  */
7424 static void
7425 tcp_reinit(tcp_t *tcp)
7426 {
7427 	mblk_t	*mp;
7428 	int 	err;
7429 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7430 
7431 	TCP_STAT(tcps, tcp_reinit_calls);
7432 
7433 	/* tcp_reinit should never be called for detached tcp_t's */
7434 	ASSERT(tcp->tcp_listener == NULL);
7435 	ASSERT((tcp->tcp_family == AF_INET &&
7436 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7437 	    (tcp->tcp_family == AF_INET6 &&
7438 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7439 	    tcp->tcp_ipversion == IPV6_VERSION)));
7440 
7441 	/* Cancel outstanding timers */
7442 	tcp_timers_stop(tcp);
7443 
7444 	/*
7445 	 * Reset everything in the state vector, after updating global
7446 	 * MIB data from instance counters.
7447 	 */
7448 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7449 	tcp->tcp_ibsegs = 0;
7450 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7451 	tcp->tcp_obsegs = 0;
7452 
7453 	tcp_close_mpp(&tcp->tcp_xmit_head);
7454 	if (tcp->tcp_snd_zcopy_aware)
7455 		tcp_zcopy_notify(tcp);
7456 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7457 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7458 	mutex_enter(&tcp->tcp_non_sq_lock);
7459 	if (tcp->tcp_flow_stopped &&
7460 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7461 		tcp_clrqfull(tcp);
7462 	}
7463 	mutex_exit(&tcp->tcp_non_sq_lock);
7464 	tcp_close_mpp(&tcp->tcp_reass_head);
7465 	tcp->tcp_reass_tail = NULL;
7466 	if (tcp->tcp_rcv_list != NULL) {
7467 		/* Free b_next chain */
7468 		tcp_close_mpp(&tcp->tcp_rcv_list);
7469 		tcp->tcp_rcv_last_head = NULL;
7470 		tcp->tcp_rcv_last_tail = NULL;
7471 		tcp->tcp_rcv_cnt = 0;
7472 	}
7473 	tcp->tcp_rcv_last_tail = NULL;
7474 
7475 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7476 		freemsg(mp);
7477 		tcp->tcp_urp_mp = NULL;
7478 	}
7479 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7480 		freemsg(mp);
7481 		tcp->tcp_urp_mark_mp = NULL;
7482 	}
7483 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7484 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7485 		freeb(tcp->tcp_fused_sigurg_mp);
7486 		tcp->tcp_fused_sigurg_mp = NULL;
7487 	}
7488 	if (tcp->tcp_ordrel_mp != NULL) {
7489 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7490 		freeb(tcp->tcp_ordrel_mp);
7491 		tcp->tcp_ordrel_mp = NULL;
7492 	}
7493 
7494 	/*
7495 	 * Following is a union with two members which are
7496 	 * identical types and size so the following cleanup
7497 	 * is enough.
7498 	 */
7499 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7500 
7501 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7502 
7503 	/*
7504 	 * The connection can't be on the tcp_time_wait_head list
7505 	 * since it is not detached.
7506 	 */
7507 	ASSERT(tcp->tcp_time_wait_next == NULL);
7508 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7509 	ASSERT(tcp->tcp_time_wait_expire == 0);
7510 
7511 	if (tcp->tcp_kssl_pending) {
7512 		tcp->tcp_kssl_pending = B_FALSE;
7513 
7514 		/* Don't reset if the initialized by bind. */
7515 		if (tcp->tcp_kssl_ent != NULL) {
7516 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7517 			    KSSL_NO_PROXY);
7518 		}
7519 	}
7520 	if (tcp->tcp_kssl_ctx != NULL) {
7521 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7522 		tcp->tcp_kssl_ctx = NULL;
7523 	}
7524 
7525 	/*
7526 	 * Reset/preserve other values
7527 	 */
7528 	tcp_reinit_values(tcp);
7529 	ipcl_hash_remove(tcp->tcp_connp);
7530 	conn_delete_ire(tcp->tcp_connp, NULL);
7531 	tcp_ipsec_cleanup(tcp);
7532 
7533 	if (tcp->tcp_connp->conn_effective_cred != NULL) {
7534 		crfree(tcp->tcp_connp->conn_effective_cred);
7535 		tcp->tcp_connp->conn_effective_cred = NULL;
7536 	}
7537 
7538 	if (tcp->tcp_conn_req_max != 0) {
7539 		/*
7540 		 * This is the case when a TLI program uses the same
7541 		 * transport end point to accept a connection.  This
7542 		 * makes the TCP both a listener and acceptor.  When
7543 		 * this connection is closed, we need to set the state
7544 		 * back to TCPS_LISTEN.  Make sure that the eager list
7545 		 * is reinitialized.
7546 		 *
7547 		 * Note that this stream is still bound to the four
7548 		 * tuples of the previous connection in IP.  If a new
7549 		 * SYN with different foreign address comes in, IP will
7550 		 * not find it and will send it to the global queue.  In
7551 		 * the global queue, TCP will do a tcp_lookup_listener()
7552 		 * to find this stream.  This works because this stream
7553 		 * is only removed from connected hash.
7554 		 *
7555 		 */
7556 		tcp->tcp_state = TCPS_LISTEN;
7557 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7558 		tcp->tcp_eager_next_drop_q0 = tcp;
7559 		tcp->tcp_eager_prev_drop_q0 = tcp;
7560 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7561 		if (tcp->tcp_family == AF_INET6) {
7562 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7563 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7564 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7565 		} else {
7566 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7567 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7568 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7569 		}
7570 	} else {
7571 		tcp->tcp_state = TCPS_BOUND;
7572 	}
7573 
7574 	/*
7575 	 * Initialize to default values
7576 	 * Can't fail since enough header template space already allocated
7577 	 * at open().
7578 	 */
7579 	err = tcp_init_values(tcp);
7580 	ASSERT(err == 0);
7581 	/* Restore state in tcp_tcph */
7582 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7583 	if (tcp->tcp_ipversion == IPV4_VERSION)
7584 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7585 	else
7586 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7587 	/*
7588 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7589 	 * since the lookup funcs can only lookup on tcp_t
7590 	 */
7591 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7592 
7593 	ASSERT(tcp->tcp_ptpbhn != NULL);
7594 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7595 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7596 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7597 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7598 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7599 }
7600 
7601 /*
7602  * Force values to zero that need be zero.
7603  * Do not touch values asociated with the BOUND or LISTEN state
7604  * since the connection will end up in that state after the reinit.
7605  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7606  * structure!
7607  */
7608 static void
7609 tcp_reinit_values(tcp)
7610 	tcp_t *tcp;
7611 {
7612 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7613 
7614 #ifndef	lint
7615 #define	DONTCARE(x)
7616 #define	PRESERVE(x)
7617 #else
7618 #define	DONTCARE(x)	((x) = (x))
7619 #define	PRESERVE(x)	((x) = (x))
7620 #endif	/* lint */
7621 
7622 	PRESERVE(tcp->tcp_bind_hash_port);
7623 	PRESERVE(tcp->tcp_bind_hash);
7624 	PRESERVE(tcp->tcp_ptpbhn);
7625 	PRESERVE(tcp->tcp_acceptor_hash);
7626 	PRESERVE(tcp->tcp_ptpahn);
7627 
7628 	/* Should be ASSERT NULL on these with new code! */
7629 	ASSERT(tcp->tcp_time_wait_next == NULL);
7630 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7631 	ASSERT(tcp->tcp_time_wait_expire == 0);
7632 	PRESERVE(tcp->tcp_state);
7633 	PRESERVE(tcp->tcp_rq);
7634 	PRESERVE(tcp->tcp_wq);
7635 
7636 	ASSERT(tcp->tcp_xmit_head == NULL);
7637 	ASSERT(tcp->tcp_xmit_last == NULL);
7638 	ASSERT(tcp->tcp_unsent == 0);
7639 	ASSERT(tcp->tcp_xmit_tail == NULL);
7640 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7641 
7642 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7643 	tcp->tcp_suna = 0;			/* Displayed in mib */
7644 	tcp->tcp_swnd = 0;
7645 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7646 
7647 	ASSERT(tcp->tcp_ibsegs == 0);
7648 	ASSERT(tcp->tcp_obsegs == 0);
7649 
7650 	if (tcp->tcp_iphc != NULL) {
7651 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7652 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7653 	}
7654 
7655 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7656 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7657 	DONTCARE(tcp->tcp_ipha);
7658 	DONTCARE(tcp->tcp_ip6h);
7659 	DONTCARE(tcp->tcp_ip_hdr_len);
7660 	DONTCARE(tcp->tcp_tcph);
7661 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7662 	tcp->tcp_valid_bits = 0;
7663 
7664 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7665 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7666 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7667 	tcp->tcp_last_rcv_lbolt = 0;
7668 
7669 	tcp->tcp_init_cwnd = 0;
7670 
7671 	tcp->tcp_urp_last_valid = 0;
7672 	tcp->tcp_hard_binding = 0;
7673 	tcp->tcp_hard_bound = 0;
7674 	PRESERVE(tcp->tcp_cred);
7675 	PRESERVE(tcp->tcp_cpid);
7676 	PRESERVE(tcp->tcp_open_time);
7677 	PRESERVE(tcp->tcp_exclbind);
7678 
7679 	tcp->tcp_fin_acked = 0;
7680 	tcp->tcp_fin_rcvd = 0;
7681 	tcp->tcp_fin_sent = 0;
7682 	tcp->tcp_ordrel_done = 0;
7683 
7684 	tcp->tcp_debug = 0;
7685 	tcp->tcp_dontroute = 0;
7686 	tcp->tcp_broadcast = 0;
7687 
7688 	tcp->tcp_useloopback = 0;
7689 	tcp->tcp_reuseaddr = 0;
7690 	tcp->tcp_oobinline = 0;
7691 	tcp->tcp_dgram_errind = 0;
7692 
7693 	tcp->tcp_detached = 0;
7694 	tcp->tcp_bind_pending = 0;
7695 	tcp->tcp_unbind_pending = 0;
7696 
7697 	tcp->tcp_snd_ws_ok = B_FALSE;
7698 	tcp->tcp_snd_ts_ok = B_FALSE;
7699 	tcp->tcp_linger = 0;
7700 	tcp->tcp_ka_enabled = 0;
7701 	tcp->tcp_zero_win_probe = 0;
7702 
7703 	tcp->tcp_loopback = 0;
7704 	tcp->tcp_refuse = 0;
7705 	tcp->tcp_localnet = 0;
7706 	tcp->tcp_syn_defense = 0;
7707 	tcp->tcp_set_timer = 0;
7708 
7709 	tcp->tcp_active_open = 0;
7710 	tcp->tcp_rexmit = B_FALSE;
7711 	tcp->tcp_xmit_zc_clean = B_FALSE;
7712 
7713 	tcp->tcp_snd_sack_ok = B_FALSE;
7714 	PRESERVE(tcp->tcp_recvdstaddr);
7715 	tcp->tcp_hwcksum = B_FALSE;
7716 
7717 	tcp->tcp_ire_ill_check_done = B_FALSE;
7718 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7719 
7720 	tcp->tcp_mdt = B_FALSE;
7721 	tcp->tcp_mdt_hdr_head = 0;
7722 	tcp->tcp_mdt_hdr_tail = 0;
7723 
7724 	tcp->tcp_conn_def_q0 = 0;
7725 	tcp->tcp_ip_forward_progress = B_FALSE;
7726 	tcp->tcp_anon_priv_bind = 0;
7727 	tcp->tcp_ecn_ok = B_FALSE;
7728 
7729 	tcp->tcp_cwr = B_FALSE;
7730 	tcp->tcp_ecn_echo_on = B_FALSE;
7731 	tcp->tcp_is_wnd_shrnk = B_FALSE;
7732 
7733 	if (tcp->tcp_sack_info != NULL) {
7734 		if (tcp->tcp_notsack_list != NULL) {
7735 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
7736 			    tcp);
7737 		}
7738 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7739 		tcp->tcp_sack_info = NULL;
7740 	}
7741 
7742 	tcp->tcp_rcv_ws = 0;
7743 	tcp->tcp_snd_ws = 0;
7744 	tcp->tcp_ts_recent = 0;
7745 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7746 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7747 	tcp->tcp_if_mtu = 0;
7748 
7749 	ASSERT(tcp->tcp_reass_head == NULL);
7750 	ASSERT(tcp->tcp_reass_tail == NULL);
7751 
7752 	tcp->tcp_cwnd_cnt = 0;
7753 
7754 	ASSERT(tcp->tcp_rcv_list == NULL);
7755 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7756 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7757 	ASSERT(tcp->tcp_rcv_cnt == 0);
7758 
7759 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7760 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7761 	tcp->tcp_csuna = 0;
7762 
7763 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7764 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7765 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7766 	tcp->tcp_rtt_update = 0;
7767 
7768 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7769 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7770 
7771 	tcp->tcp_rack = 0;			/* Displayed in mib */
7772 	tcp->tcp_rack_cnt = 0;
7773 	tcp->tcp_rack_cur_max = 0;
7774 	tcp->tcp_rack_abs_max = 0;
7775 
7776 	tcp->tcp_max_swnd = 0;
7777 
7778 	ASSERT(tcp->tcp_listener == NULL);
7779 
7780 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7781 
7782 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7783 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7784 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7785 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7786 
7787 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7788 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7789 	PRESERVE(tcp->tcp_conn_req_max);
7790 	PRESERVE(tcp->tcp_conn_req_seqnum);
7791 
7792 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7793 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7794 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7795 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7796 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7797 
7798 	tcp->tcp_lingertime = 0;
7799 
7800 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7801 	ASSERT(tcp->tcp_urp_mp == NULL);
7802 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7803 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7804 
7805 	ASSERT(tcp->tcp_eager_next_q == NULL);
7806 	ASSERT(tcp->tcp_eager_last_q == NULL);
7807 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7808 	    tcp->tcp_eager_prev_q0 == NULL) ||
7809 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7810 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7811 
7812 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7813 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7814 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7815 
7816 	tcp->tcp_client_errno = 0;
7817 
7818 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7819 
7820 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7821 
7822 	PRESERVE(tcp->tcp_bound_source_v6);
7823 	tcp->tcp_last_sent_len = 0;
7824 	tcp->tcp_dupack_cnt = 0;
7825 
7826 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7827 	PRESERVE(tcp->tcp_lport);
7828 
7829 	PRESERVE(tcp->tcp_acceptor_lockp);
7830 
7831 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7832 	PRESERVE(tcp->tcp_acceptor_id);
7833 	DONTCARE(tcp->tcp_ipsec_overhead);
7834 
7835 	PRESERVE(tcp->tcp_family);
7836 	if (tcp->tcp_family == AF_INET6) {
7837 		tcp->tcp_ipversion = IPV6_VERSION;
7838 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7839 	} else {
7840 		tcp->tcp_ipversion = IPV4_VERSION;
7841 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7842 	}
7843 
7844 	tcp->tcp_bound_if = 0;
7845 	tcp->tcp_ipv6_recvancillary = 0;
7846 	tcp->tcp_recvifindex = 0;
7847 	tcp->tcp_recvhops = 0;
7848 	tcp->tcp_closed = 0;
7849 	tcp->tcp_cleandeathtag = 0;
7850 	if (tcp->tcp_hopopts != NULL) {
7851 		mi_free(tcp->tcp_hopopts);
7852 		tcp->tcp_hopopts = NULL;
7853 		tcp->tcp_hopoptslen = 0;
7854 	}
7855 	ASSERT(tcp->tcp_hopoptslen == 0);
7856 	if (tcp->tcp_dstopts != NULL) {
7857 		mi_free(tcp->tcp_dstopts);
7858 		tcp->tcp_dstopts = NULL;
7859 		tcp->tcp_dstoptslen = 0;
7860 	}
7861 	ASSERT(tcp->tcp_dstoptslen == 0);
7862 	if (tcp->tcp_rtdstopts != NULL) {
7863 		mi_free(tcp->tcp_rtdstopts);
7864 		tcp->tcp_rtdstopts = NULL;
7865 		tcp->tcp_rtdstoptslen = 0;
7866 	}
7867 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7868 	if (tcp->tcp_rthdr != NULL) {
7869 		mi_free(tcp->tcp_rthdr);
7870 		tcp->tcp_rthdr = NULL;
7871 		tcp->tcp_rthdrlen = 0;
7872 	}
7873 	ASSERT(tcp->tcp_rthdrlen == 0);
7874 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7875 
7876 	/* Reset fusion-related fields */
7877 	tcp->tcp_fused = B_FALSE;
7878 	tcp->tcp_unfusable = B_FALSE;
7879 	tcp->tcp_fused_sigurg = B_FALSE;
7880 	tcp->tcp_loopback_peer = NULL;
7881 
7882 	tcp->tcp_lso = B_FALSE;
7883 
7884 	tcp->tcp_in_ack_unsent = 0;
7885 	tcp->tcp_cork = B_FALSE;
7886 	tcp->tcp_tconnind_started = B_FALSE;
7887 
7888 	PRESERVE(tcp->tcp_squeue_bytes);
7889 
7890 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7891 	ASSERT(!tcp->tcp_kssl_pending);
7892 	PRESERVE(tcp->tcp_kssl_ent);
7893 
7894 	tcp->tcp_closemp_used = B_FALSE;
7895 
7896 	PRESERVE(tcp->tcp_rsrv_mp);
7897 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7898 
7899 #ifdef DEBUG
7900 	DONTCARE(tcp->tcmp_stk[0]);
7901 #endif
7902 
7903 	PRESERVE(tcp->tcp_connid);
7904 
7905 
7906 #undef	DONTCARE
7907 #undef	PRESERVE
7908 }
7909 
7910 /*
7911  * Allocate necessary resources and initialize state vector.
7912  * Guaranteed not to fail so that when an error is returned,
7913  * the caller doesn't need to do any additional cleanup.
7914  */
7915 int
7916 tcp_init(tcp_t *tcp, queue_t *q)
7917 {
7918 	int	err;
7919 
7920 	tcp->tcp_rq = q;
7921 	tcp->tcp_wq = WR(q);
7922 	tcp->tcp_state = TCPS_IDLE;
7923 	if ((err = tcp_init_values(tcp)) != 0)
7924 		tcp_timers_stop(tcp);
7925 	return (err);
7926 }
7927 
7928 static int
7929 tcp_init_values(tcp_t *tcp)
7930 {
7931 	int	err;
7932 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7933 
7934 	ASSERT((tcp->tcp_family == AF_INET &&
7935 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7936 	    (tcp->tcp_family == AF_INET6 &&
7937 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7938 	    tcp->tcp_ipversion == IPV6_VERSION)));
7939 
7940 	/*
7941 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7942 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7943 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7944 	 * during first few transmissions of a connection as seen in slow
7945 	 * links.
7946 	 */
7947 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7948 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7949 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7950 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7951 	    tcps->tcps_conn_grace_period;
7952 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7953 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7954 	tcp->tcp_timer_backoff = 0;
7955 	tcp->tcp_ms_we_have_waited = 0;
7956 	tcp->tcp_last_recv_time = lbolt;
7957 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7958 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7959 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7960 
7961 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7962 
7963 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7964 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7965 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7966 	/*
7967 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7968 	 * passive open.
7969 	 */
7970 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7971 
7972 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7973 
7974 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7975 
7976 	tcp->tcp_mdt_hdr_head = 0;
7977 	tcp->tcp_mdt_hdr_tail = 0;
7978 
7979 	/* Reset fusion-related fields */
7980 	tcp->tcp_fused = B_FALSE;
7981 	tcp->tcp_unfusable = B_FALSE;
7982 	tcp->tcp_fused_sigurg = B_FALSE;
7983 	tcp->tcp_loopback_peer = NULL;
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 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
8002 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
8003 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
8004 
8005 	tcp->tcp_cork = B_FALSE;
8006 	/*
8007 	 * Init the tcp_debug option.  This value determines whether TCP
8008 	 * calls strlog() to print out debug messages.  Doing this
8009 	 * initialization here means that this value is not inherited thru
8010 	 * tcp_reinit().
8011 	 */
8012 	tcp->tcp_debug = tcps->tcps_dbg;
8013 
8014 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8015 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8016 
8017 	return (0);
8018 }
8019 
8020 /*
8021  * Initialize the IPv4 header. Loses any record of any IP options.
8022  */
8023 static int
8024 tcp_header_init_ipv4(tcp_t *tcp)
8025 {
8026 	tcph_t		*tcph;
8027 	uint32_t	sum;
8028 	conn_t		*connp;
8029 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8030 
8031 	/*
8032 	 * This is a simple initialization. If there's
8033 	 * already a template, it should never be too small,
8034 	 * so reuse it.  Otherwise, allocate space for the new one.
8035 	 */
8036 	if (tcp->tcp_iphc == NULL) {
8037 		ASSERT(tcp->tcp_iphc_len == 0);
8038 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8039 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8040 		if (tcp->tcp_iphc == NULL) {
8041 			tcp->tcp_iphc_len = 0;
8042 			return (ENOMEM);
8043 		}
8044 	}
8045 
8046 	/* options are gone; may need a new label */
8047 	connp = tcp->tcp_connp;
8048 	connp->conn_mlp_type = mlptSingle;
8049 	connp->conn_ulp_labeled = !is_system_labeled();
8050 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8051 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8052 	tcp->tcp_ip6h = NULL;
8053 	tcp->tcp_ipversion = IPV4_VERSION;
8054 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8055 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8056 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8057 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8058 	tcp->tcp_ipha->ipha_version_and_hdr_length
8059 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8060 	tcp->tcp_ipha->ipha_ident = 0;
8061 
8062 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8063 	tcp->tcp_tos = 0;
8064 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8065 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8066 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8067 
8068 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8069 	tcp->tcp_tcph = tcph;
8070 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8071 	/*
8072 	 * IP wants our header length in the checksum field to
8073 	 * allow it to perform a single pseudo-header+checksum
8074 	 * calculation on behalf of TCP.
8075 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8076 	 */
8077 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8078 	sum = (sum >> 16) + (sum & 0xFFFF);
8079 	U16_TO_ABE16(sum, tcph->th_sum);
8080 	return (0);
8081 }
8082 
8083 /*
8084  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8085  */
8086 static int
8087 tcp_header_init_ipv6(tcp_t *tcp)
8088 {
8089 	tcph_t	*tcph;
8090 	uint32_t	sum;
8091 	conn_t	*connp;
8092 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8093 
8094 	/*
8095 	 * This is a simple initialization. If there's
8096 	 * already a template, it should never be too small,
8097 	 * so reuse it. Otherwise, allocate space for the new one.
8098 	 * Ensure that there is enough space to "downgrade" the tcp_t
8099 	 * to an IPv4 tcp_t. This requires having space for a full load
8100 	 * of IPv4 options, as well as a full load of TCP options
8101 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8102 	 * than a v6 header and a TCP header with a full load of TCP options
8103 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8104 	 * We want to avoid reallocation in the "downgraded" case when
8105 	 * processing outbound IPv4 options.
8106 	 */
8107 	if (tcp->tcp_iphc == NULL) {
8108 		ASSERT(tcp->tcp_iphc_len == 0);
8109 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8110 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8111 		if (tcp->tcp_iphc == NULL) {
8112 			tcp->tcp_iphc_len = 0;
8113 			return (ENOMEM);
8114 		}
8115 	}
8116 
8117 	/* options are gone; may need a new label */
8118 	connp = tcp->tcp_connp;
8119 	connp->conn_mlp_type = mlptSingle;
8120 	connp->conn_ulp_labeled = !is_system_labeled();
8121 
8122 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8123 	tcp->tcp_ipversion = IPV6_VERSION;
8124 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8125 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8126 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8127 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8128 	tcp->tcp_ipha = NULL;
8129 
8130 	/* Initialize the header template */
8131 
8132 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8133 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8134 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8135 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8136 
8137 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8138 	tcp->tcp_tcph = tcph;
8139 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8140 	/*
8141 	 * IP wants our header length in the checksum field to
8142 	 * allow it to perform a single psuedo-header+checksum
8143 	 * calculation on behalf of TCP.
8144 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8145 	 */
8146 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8147 	sum = (sum >> 16) + (sum & 0xFFFF);
8148 	U16_TO_ABE16(sum, tcph->th_sum);
8149 	return (0);
8150 }
8151 
8152 /* At minimum we need 8 bytes in the TCP header for the lookup */
8153 #define	ICMP_MIN_TCP_HDR	8
8154 
8155 /*
8156  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8157  * passed up by IP. The message is always received on the correct tcp_t.
8158  * Assumes that IP has pulled up everything up to and including the ICMP header.
8159  */
8160 void
8161 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8162 {
8163 	icmph_t *icmph;
8164 	ipha_t	*ipha;
8165 	int	iph_hdr_length;
8166 	tcph_t	*tcph;
8167 	boolean_t ipsec_mctl = B_FALSE;
8168 	boolean_t secure;
8169 	mblk_t *first_mp = mp;
8170 	int32_t new_mss;
8171 	uint32_t ratio;
8172 	size_t mp_size = MBLKL(mp);
8173 	uint32_t seg_seq;
8174 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8175 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8176 
8177 	/* Assume IP provides aligned packets - otherwise toss */
8178 	if (!OK_32PTR(mp->b_rptr)) {
8179 		freemsg(mp);
8180 		return;
8181 	}
8182 
8183 	/*
8184 	 * Since ICMP errors are normal data marked with M_CTL when sent
8185 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8186 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8187 	 */
8188 	if ((mp_size == sizeof (ipsec_info_t)) &&
8189 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8190 		ASSERT(mp->b_cont != NULL);
8191 		mp = mp->b_cont;
8192 		/* IP should have done this */
8193 		ASSERT(OK_32PTR(mp->b_rptr));
8194 		mp_size = MBLKL(mp);
8195 		ipsec_mctl = B_TRUE;
8196 	}
8197 
8198 	/*
8199 	 * Verify that we have a complete outer IP header. If not, drop it.
8200 	 */
8201 	if (mp_size < sizeof (ipha_t)) {
8202 noticmpv4:
8203 		freemsg(first_mp);
8204 		return;
8205 	}
8206 
8207 	ipha = (ipha_t *)mp->b_rptr;
8208 	/*
8209 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8210 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8211 	 */
8212 	switch (IPH_HDR_VERSION(ipha)) {
8213 	case IPV6_VERSION:
8214 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8215 		return;
8216 	case IPV4_VERSION:
8217 		break;
8218 	default:
8219 		goto noticmpv4;
8220 	}
8221 
8222 	/* Skip past the outer IP and ICMP headers */
8223 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8224 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8225 	/*
8226 	 * If we don't have the correct outer IP header length or if the ULP
8227 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8228 	 * send it upstream.
8229 	 */
8230 	if (iph_hdr_length < sizeof (ipha_t) ||
8231 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8232 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8233 		goto noticmpv4;
8234 	}
8235 	ipha = (ipha_t *)&icmph[1];
8236 
8237 	/* Skip past the inner IP and find the ULP header */
8238 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8239 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8240 	/*
8241 	 * If we don't have the correct inner IP header length or if the ULP
8242 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8243 	 * bytes of TCP header, drop it.
8244 	 */
8245 	if (iph_hdr_length < sizeof (ipha_t) ||
8246 	    ipha->ipha_protocol != IPPROTO_TCP ||
8247 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8248 		goto noticmpv4;
8249 	}
8250 
8251 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8252 		if (ipsec_mctl) {
8253 			secure = ipsec_in_is_secure(first_mp);
8254 		} else {
8255 			secure = B_FALSE;
8256 		}
8257 		if (secure) {
8258 			/*
8259 			 * If we are willing to accept this in clear
8260 			 * we don't have to verify policy.
8261 			 */
8262 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8263 				if (!tcp_check_policy(tcp, first_mp,
8264 				    ipha, NULL, secure, ipsec_mctl)) {
8265 					/*
8266 					 * tcp_check_policy called
8267 					 * ip_drop_packet() on failure.
8268 					 */
8269 					return;
8270 				}
8271 			}
8272 		}
8273 	} else if (ipsec_mctl) {
8274 		/*
8275 		 * This is a hard_bound connection. IP has already
8276 		 * verified policy. We don't have to do it again.
8277 		 */
8278 		freeb(first_mp);
8279 		first_mp = mp;
8280 		ipsec_mctl = B_FALSE;
8281 	}
8282 
8283 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8284 	/*
8285 	 * TCP SHOULD check that the TCP sequence number contained in
8286 	 * payload of the ICMP error message is within the range
8287 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8288 	 */
8289 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8290 		/*
8291 		 * The ICMP message is bogus, just drop it.  But if this is
8292 		 * an ICMP too big message, IP has already changed
8293 		 * the ire_max_frag to the bogus value.  We need to change
8294 		 * it back.
8295 		 */
8296 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8297 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8298 			conn_t *connp = tcp->tcp_connp;
8299 			ire_t *ire;
8300 			int flag;
8301 
8302 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8303 				flag = tcp->tcp_ipha->
8304 				    ipha_fragment_offset_and_flags;
8305 			} else {
8306 				flag = 0;
8307 			}
8308 			mutex_enter(&connp->conn_lock);
8309 			if ((ire = connp->conn_ire_cache) != NULL) {
8310 				mutex_enter(&ire->ire_lock);
8311 				mutex_exit(&connp->conn_lock);
8312 				ire->ire_max_frag = tcp->tcp_if_mtu;
8313 				ire->ire_frag_flag |= flag;
8314 				mutex_exit(&ire->ire_lock);
8315 			} else {
8316 				mutex_exit(&connp->conn_lock);
8317 			}
8318 		}
8319 		goto noticmpv4;
8320 	}
8321 
8322 	switch (icmph->icmph_type) {
8323 	case ICMP_DEST_UNREACHABLE:
8324 		switch (icmph->icmph_code) {
8325 		case ICMP_FRAGMENTATION_NEEDED:
8326 			/*
8327 			 * Reduce the MSS based on the new MTU.  This will
8328 			 * eliminate any fragmentation locally.
8329 			 * N.B.  There may well be some funny side-effects on
8330 			 * the local send policy and the remote receive policy.
8331 			 * Pending further research, we provide
8332 			 * tcp_ignore_path_mtu just in case this proves
8333 			 * disastrous somewhere.
8334 			 *
8335 			 * After updating the MSS, retransmit part of the
8336 			 * dropped segment using the new mss by calling
8337 			 * tcp_wput_data().  Need to adjust all those
8338 			 * params to make sure tcp_wput_data() work properly.
8339 			 */
8340 			if (tcps->tcps_ignore_path_mtu ||
8341 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8342 				break;
8343 
8344 			/*
8345 			 * Decrease the MSS by time stamp options
8346 			 * IP options and IPSEC options. tcp_hdr_len
8347 			 * includes time stamp option and IP option
8348 			 * length.  Note that new_mss may be negative
8349 			 * if tcp_ipsec_overhead is large and the
8350 			 * icmph_du_mtu is the minimum value, which is 68.
8351 			 */
8352 			new_mss = ntohs(icmph->icmph_du_mtu) -
8353 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8354 
8355 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8356 			    new_mss);
8357 
8358 			/*
8359 			 * Only update the MSS if the new one is
8360 			 * smaller than the previous one.  This is
8361 			 * to avoid problems when getting multiple
8362 			 * ICMP errors for the same MTU.
8363 			 */
8364 			if (new_mss >= tcp->tcp_mss)
8365 				break;
8366 
8367 			/*
8368 			 * Note that we are using the template header's DF
8369 			 * bit in the fast path sending.  So we need to compare
8370 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8371 			 * And stop doing IPv4 PMTUd if new_mss is less than
8372 			 * MAX(tcps_mss_min, ip_pmtu_min).
8373 			 */
8374 			if (new_mss < tcps->tcps_mss_min ||
8375 			    new_mss < ipst->ips_ip_pmtu_min) {
8376 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8377 				    0;
8378 			}
8379 
8380 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8381 			ASSERT(ratio >= 1);
8382 			tcp_mss_set(tcp, new_mss, B_TRUE);
8383 
8384 			/*
8385 			 * Make sure we have something to
8386 			 * send.
8387 			 */
8388 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8389 			    (tcp->tcp_xmit_head != NULL)) {
8390 				/*
8391 				 * Shrink tcp_cwnd in
8392 				 * proportion to the old MSS/new MSS.
8393 				 */
8394 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8395 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8396 				    (tcp->tcp_unsent == 0)) {
8397 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8398 				} else {
8399 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8400 				}
8401 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8402 				tcp->tcp_rexmit = B_TRUE;
8403 				tcp->tcp_dupack_cnt = 0;
8404 				tcp->tcp_snd_burst = TCP_CWND_SS;
8405 				tcp_ss_rexmit(tcp);
8406 			}
8407 			break;
8408 		case ICMP_PORT_UNREACHABLE:
8409 		case ICMP_PROTOCOL_UNREACHABLE:
8410 			switch (tcp->tcp_state) {
8411 			case TCPS_SYN_SENT:
8412 			case TCPS_SYN_RCVD:
8413 				/*
8414 				 * ICMP can snipe away incipient
8415 				 * TCP connections as long as
8416 				 * seq number is same as initial
8417 				 * send seq number.
8418 				 */
8419 				if (seg_seq == tcp->tcp_iss) {
8420 					(void) tcp_clean_death(tcp,
8421 					    ECONNREFUSED, 6);
8422 				}
8423 				break;
8424 			}
8425 			break;
8426 		case ICMP_HOST_UNREACHABLE:
8427 		case ICMP_NET_UNREACHABLE:
8428 			/* Record the error in case we finally time out. */
8429 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8430 				tcp->tcp_client_errno = EHOSTUNREACH;
8431 			else
8432 				tcp->tcp_client_errno = ENETUNREACH;
8433 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8434 				if (tcp->tcp_listener != NULL &&
8435 				    tcp->tcp_listener->tcp_syn_defense) {
8436 					/*
8437 					 * Ditch the half-open connection if we
8438 					 * suspect a SYN attack is under way.
8439 					 */
8440 					tcp_ip_ire_mark_advice(tcp);
8441 					(void) tcp_clean_death(tcp,
8442 					    tcp->tcp_client_errno, 7);
8443 				}
8444 			}
8445 			break;
8446 		default:
8447 			break;
8448 		}
8449 		break;
8450 	case ICMP_SOURCE_QUENCH: {
8451 		/*
8452 		 * use a global boolean to control
8453 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8454 		 * The default is false.
8455 		 */
8456 		if (tcp_icmp_source_quench) {
8457 			/*
8458 			 * Reduce the sending rate as if we got a
8459 			 * retransmit timeout
8460 			 */
8461 			uint32_t npkt;
8462 
8463 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8464 			    tcp->tcp_mss;
8465 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8466 			tcp->tcp_cwnd = tcp->tcp_mss;
8467 			tcp->tcp_cwnd_cnt = 0;
8468 		}
8469 		break;
8470 	}
8471 	}
8472 	freemsg(first_mp);
8473 }
8474 
8475 /*
8476  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8477  * error messages passed up by IP.
8478  * Assumes that IP has pulled up all the extension headers as well
8479  * as the ICMPv6 header.
8480  */
8481 static void
8482 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8483 {
8484 	icmp6_t *icmp6;
8485 	ip6_t	*ip6h;
8486 	uint16_t	iph_hdr_length;
8487 	tcpha_t	*tcpha;
8488 	uint8_t	*nexthdrp;
8489 	uint32_t new_mss;
8490 	uint32_t ratio;
8491 	boolean_t secure;
8492 	mblk_t *first_mp = mp;
8493 	size_t mp_size;
8494 	uint32_t seg_seq;
8495 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8496 
8497 	/*
8498 	 * The caller has determined if this is an IPSEC_IN packet and
8499 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8500 	 */
8501 	if (ipsec_mctl)
8502 		mp = mp->b_cont;
8503 
8504 	mp_size = MBLKL(mp);
8505 
8506 	/*
8507 	 * Verify that we have a complete IP header. If not, send it upstream.
8508 	 */
8509 	if (mp_size < sizeof (ip6_t)) {
8510 noticmpv6:
8511 		freemsg(first_mp);
8512 		return;
8513 	}
8514 
8515 	/*
8516 	 * Verify this is an ICMPV6 packet, else send it upstream.
8517 	 */
8518 	ip6h = (ip6_t *)mp->b_rptr;
8519 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8520 		iph_hdr_length = IPV6_HDR_LEN;
8521 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8522 	    &nexthdrp) ||
8523 	    *nexthdrp != IPPROTO_ICMPV6) {
8524 		goto noticmpv6;
8525 	}
8526 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8527 	ip6h = (ip6_t *)&icmp6[1];
8528 	/*
8529 	 * Verify if we have a complete ICMP and inner IP header.
8530 	 */
8531 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8532 		goto noticmpv6;
8533 
8534 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8535 		goto noticmpv6;
8536 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8537 	/*
8538 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8539 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8540 	 * packet.
8541 	 */
8542 	if ((*nexthdrp != IPPROTO_TCP) ||
8543 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8544 		goto noticmpv6;
8545 	}
8546 
8547 	/*
8548 	 * ICMP errors come on the right queue or come on
8549 	 * listener/global queue for detached connections and
8550 	 * get switched to the right queue. If it comes on the
8551 	 * right queue, policy check has already been done by IP
8552 	 * and thus free the first_mp without verifying the policy.
8553 	 * If it has come for a non-hard bound connection, we need
8554 	 * to verify policy as IP may not have done it.
8555 	 */
8556 	if (!tcp->tcp_hard_bound) {
8557 		if (ipsec_mctl) {
8558 			secure = ipsec_in_is_secure(first_mp);
8559 		} else {
8560 			secure = B_FALSE;
8561 		}
8562 		if (secure) {
8563 			/*
8564 			 * If we are willing to accept this in clear
8565 			 * we don't have to verify policy.
8566 			 */
8567 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8568 				if (!tcp_check_policy(tcp, first_mp,
8569 				    NULL, ip6h, secure, ipsec_mctl)) {
8570 					/*
8571 					 * tcp_check_policy called
8572 					 * ip_drop_packet() on failure.
8573 					 */
8574 					return;
8575 				}
8576 			}
8577 		}
8578 	} else if (ipsec_mctl) {
8579 		/*
8580 		 * This is a hard_bound connection. IP has already
8581 		 * verified policy. We don't have to do it again.
8582 		 */
8583 		freeb(first_mp);
8584 		first_mp = mp;
8585 		ipsec_mctl = B_FALSE;
8586 	}
8587 
8588 	seg_seq = ntohl(tcpha->tha_seq);
8589 	/*
8590 	 * TCP SHOULD check that the TCP sequence number contained in
8591 	 * payload of the ICMP error message is within the range
8592 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8593 	 */
8594 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8595 		/*
8596 		 * If the ICMP message is bogus, should we kill the
8597 		 * connection, or should we just drop the bogus ICMP
8598 		 * message? It would probably make more sense to just
8599 		 * drop the message so that if this one managed to get
8600 		 * in, the real connection should not suffer.
8601 		 */
8602 		goto noticmpv6;
8603 	}
8604 
8605 	switch (icmp6->icmp6_type) {
8606 	case ICMP6_PACKET_TOO_BIG:
8607 		/*
8608 		 * Reduce the MSS based on the new MTU.  This will
8609 		 * eliminate any fragmentation locally.
8610 		 * N.B.  There may well be some funny side-effects on
8611 		 * the local send policy and the remote receive policy.
8612 		 * Pending further research, we provide
8613 		 * tcp_ignore_path_mtu just in case this proves
8614 		 * disastrous somewhere.
8615 		 *
8616 		 * After updating the MSS, retransmit part of the
8617 		 * dropped segment using the new mss by calling
8618 		 * tcp_wput_data().  Need to adjust all those
8619 		 * params to make sure tcp_wput_data() work properly.
8620 		 */
8621 		if (tcps->tcps_ignore_path_mtu)
8622 			break;
8623 
8624 		/*
8625 		 * Decrease the MSS by time stamp options
8626 		 * IP options and IPSEC options. tcp_hdr_len
8627 		 * includes time stamp option and IP option
8628 		 * length.
8629 		 */
8630 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8631 		    tcp->tcp_ipsec_overhead;
8632 
8633 		/*
8634 		 * Only update the MSS if the new one is
8635 		 * smaller than the previous one.  This is
8636 		 * to avoid problems when getting multiple
8637 		 * ICMP errors for the same MTU.
8638 		 */
8639 		if (new_mss >= tcp->tcp_mss)
8640 			break;
8641 
8642 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8643 		ASSERT(ratio >= 1);
8644 		tcp_mss_set(tcp, new_mss, B_TRUE);
8645 
8646 		/*
8647 		 * Make sure we have something to
8648 		 * send.
8649 		 */
8650 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8651 		    (tcp->tcp_xmit_head != NULL)) {
8652 			/*
8653 			 * Shrink tcp_cwnd in
8654 			 * proportion to the old MSS/new MSS.
8655 			 */
8656 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8657 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8658 			    (tcp->tcp_unsent == 0)) {
8659 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8660 			} else {
8661 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8662 			}
8663 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8664 			tcp->tcp_rexmit = B_TRUE;
8665 			tcp->tcp_dupack_cnt = 0;
8666 			tcp->tcp_snd_burst = TCP_CWND_SS;
8667 			tcp_ss_rexmit(tcp);
8668 		}
8669 		break;
8670 
8671 	case ICMP6_DST_UNREACH:
8672 		switch (icmp6->icmp6_code) {
8673 		case ICMP6_DST_UNREACH_NOPORT:
8674 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8675 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8676 			    (seg_seq == tcp->tcp_iss)) {
8677 				(void) tcp_clean_death(tcp,
8678 				    ECONNREFUSED, 8);
8679 			}
8680 			break;
8681 
8682 		case ICMP6_DST_UNREACH_ADMIN:
8683 		case ICMP6_DST_UNREACH_NOROUTE:
8684 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8685 		case ICMP6_DST_UNREACH_ADDR:
8686 			/* Record the error in case we finally time out. */
8687 			tcp->tcp_client_errno = EHOSTUNREACH;
8688 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8689 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8690 			    (seg_seq == tcp->tcp_iss)) {
8691 				if (tcp->tcp_listener != NULL &&
8692 				    tcp->tcp_listener->tcp_syn_defense) {
8693 					/*
8694 					 * Ditch the half-open connection if we
8695 					 * suspect a SYN attack is under way.
8696 					 */
8697 					tcp_ip_ire_mark_advice(tcp);
8698 					(void) tcp_clean_death(tcp,
8699 					    tcp->tcp_client_errno, 9);
8700 				}
8701 			}
8702 
8703 
8704 			break;
8705 		default:
8706 			break;
8707 		}
8708 		break;
8709 
8710 	case ICMP6_PARAM_PROB:
8711 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8712 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8713 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8714 		    (uchar_t *)nexthdrp) {
8715 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8716 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8717 				(void) tcp_clean_death(tcp,
8718 				    ECONNREFUSED, 10);
8719 			}
8720 			break;
8721 		}
8722 		break;
8723 
8724 	case ICMP6_TIME_EXCEEDED:
8725 	default:
8726 		break;
8727 	}
8728 	freemsg(first_mp);
8729 }
8730 
8731 /*
8732  * Notify IP that we are having trouble with this connection.  IP should
8733  * blow the IRE away and start over.
8734  */
8735 static void
8736 tcp_ip_notify(tcp_t *tcp)
8737 {
8738 	struct iocblk	*iocp;
8739 	ipid_t	*ipid;
8740 	mblk_t	*mp;
8741 
8742 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8743 	if (tcp->tcp_ipversion == IPV6_VERSION)
8744 		return;
8745 
8746 	mp = mkiocb(IP_IOCTL);
8747 	if (mp == NULL)
8748 		return;
8749 
8750 	iocp = (struct iocblk *)mp->b_rptr;
8751 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8752 
8753 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8754 	if (!mp->b_cont) {
8755 		freeb(mp);
8756 		return;
8757 	}
8758 
8759 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8760 	mp->b_cont->b_wptr += iocp->ioc_count;
8761 	bzero(ipid, sizeof (*ipid));
8762 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8763 	ipid->ipid_ire_type = IRE_CACHE;
8764 	ipid->ipid_addr_offset = sizeof (ipid_t);
8765 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8766 	/*
8767 	 * Note: in the case of source routing we want to blow away the
8768 	 * route to the first source route hop.
8769 	 */
8770 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8771 	    sizeof (tcp->tcp_ipha->ipha_dst));
8772 
8773 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8774 }
8775 
8776 /* Unlink and return any mblk that looks like it contains an ire */
8777 static mblk_t *
8778 tcp_ire_mp(mblk_t **mpp)
8779 {
8780 	mblk_t 	*mp = *mpp;
8781 	mblk_t	*prev_mp = NULL;
8782 
8783 	for (;;) {
8784 		switch (DB_TYPE(mp)) {
8785 		case IRE_DB_TYPE:
8786 		case IRE_DB_REQ_TYPE:
8787 			if (mp == *mpp) {
8788 				*mpp = mp->b_cont;
8789 			} else {
8790 				prev_mp->b_cont = mp->b_cont;
8791 			}
8792 			mp->b_cont = NULL;
8793 			return (mp);
8794 		default:
8795 			break;
8796 		}
8797 		prev_mp = mp;
8798 		mp = mp->b_cont;
8799 		if (mp == NULL)
8800 			break;
8801 	}
8802 	return (mp);
8803 }
8804 
8805 /*
8806  * Timer callback routine for keepalive probe.  We do a fake resend of
8807  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8808  * check to see if we have heard anything from the other end for the last
8809  * RTO period.  If we have, set the timer to expire for another
8810  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8811  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8812  * the timeout if we have not heard from the other side.  If for more than
8813  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8814  * kill the connection unless the keepalive abort threshold is 0.  In
8815  * that case, we will probe "forever."
8816  */
8817 static void
8818 tcp_keepalive_killer(void *arg)
8819 {
8820 	mblk_t	*mp;
8821 	conn_t	*connp = (conn_t *)arg;
8822 	tcp_t  	*tcp = connp->conn_tcp;
8823 	int32_t	firetime;
8824 	int32_t	idletime;
8825 	int32_t	ka_intrvl;
8826 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8827 
8828 	tcp->tcp_ka_tid = 0;
8829 
8830 	if (tcp->tcp_fused)
8831 		return;
8832 
8833 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8834 	ka_intrvl = tcp->tcp_ka_interval;
8835 
8836 	/*
8837 	 * Keepalive probe should only be sent if the application has not
8838 	 * done a close on the connection.
8839 	 */
8840 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8841 		return;
8842 	}
8843 	/* Timer fired too early, restart it. */
8844 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8845 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8846 		    MSEC_TO_TICK(ka_intrvl));
8847 		return;
8848 	}
8849 
8850 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8851 	/*
8852 	 * If we have not heard from the other side for a long
8853 	 * time, kill the connection unless the keepalive abort
8854 	 * threshold is 0.  In that case, we will probe "forever."
8855 	 */
8856 	if (tcp->tcp_ka_abort_thres != 0 &&
8857 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8858 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8859 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8860 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8861 		return;
8862 	}
8863 
8864 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8865 	    idletime >= ka_intrvl) {
8866 		/* Fake resend of last ACKed byte. */
8867 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8868 
8869 		if (mp1 != NULL) {
8870 			*mp1->b_wptr++ = '\0';
8871 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8872 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8873 			freeb(mp1);
8874 			/*
8875 			 * if allocation failed, fall through to start the
8876 			 * timer back.
8877 			 */
8878 			if (mp != NULL) {
8879 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8880 				BUMP_MIB(&tcps->tcps_mib,
8881 				    tcpTimKeepaliveProbe);
8882 				if (tcp->tcp_ka_last_intrvl != 0) {
8883 					int max;
8884 					/*
8885 					 * We should probe again at least
8886 					 * in ka_intrvl, but not more than
8887 					 * tcp_rexmit_interval_max.
8888 					 */
8889 					max = tcps->tcps_rexmit_interval_max;
8890 					firetime = MIN(ka_intrvl - 1,
8891 					    tcp->tcp_ka_last_intrvl << 1);
8892 					if (firetime > max)
8893 						firetime = max;
8894 				} else {
8895 					firetime = tcp->tcp_rto;
8896 				}
8897 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8898 				    tcp_keepalive_killer,
8899 				    MSEC_TO_TICK(firetime));
8900 				tcp->tcp_ka_last_intrvl = firetime;
8901 				return;
8902 			}
8903 		}
8904 	} else {
8905 		tcp->tcp_ka_last_intrvl = 0;
8906 	}
8907 
8908 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8909 	if ((firetime = ka_intrvl - idletime) < 0) {
8910 		firetime = ka_intrvl;
8911 	}
8912 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8913 	    MSEC_TO_TICK(firetime));
8914 }
8915 
8916 int
8917 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8918 {
8919 	queue_t	*q = tcp->tcp_rq;
8920 	int32_t	mss = tcp->tcp_mss;
8921 	int	maxpsz;
8922 	conn_t	*connp = tcp->tcp_connp;
8923 
8924 	if (TCP_IS_DETACHED(tcp))
8925 		return (mss);
8926 	if (tcp->tcp_fused) {
8927 		maxpsz = tcp_fuse_maxpsz(tcp);
8928 		mss = INFPSZ;
8929 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8930 		/*
8931 		 * Set the sd_qn_maxpsz according to the socket send buffer
8932 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8933 		 * instruct the stream head to copyin user data into contiguous
8934 		 * kernel-allocated buffers without breaking it up into smaller
8935 		 * chunks.  We round up the buffer size to the nearest SMSS.
8936 		 */
8937 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8938 		if (tcp->tcp_kssl_ctx == NULL)
8939 			mss = INFPSZ;
8940 		else
8941 			mss = SSL3_MAX_RECORD_LEN;
8942 	} else {
8943 		/*
8944 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8945 		 * (and a multiple of the mss).  This instructs the stream
8946 		 * head to break down larger than SMSS writes into SMSS-
8947 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8948 		 */
8949 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8950 		maxpsz = tcp->tcp_maxpsz * mss;
8951 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8952 			maxpsz = tcp->tcp_xmit_hiwater/2;
8953 			/* Round up to nearest mss */
8954 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8955 		}
8956 	}
8957 
8958 	(void) proto_set_maxpsz(q, connp, maxpsz);
8959 	if (!(IPCL_IS_NONSTR(connp))) {
8960 		/* XXX do it in set_maxpsz()? */
8961 		tcp->tcp_wq->q_maxpsz = maxpsz;
8962 	}
8963 
8964 	if (set_maxblk)
8965 		(void) proto_set_tx_maxblk(q, connp, mss);
8966 	return (mss);
8967 }
8968 
8969 /*
8970  * Extract option values from a tcp header.  We put any found values into the
8971  * tcpopt struct and return a bitmask saying which options were found.
8972  */
8973 static int
8974 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8975 {
8976 	uchar_t		*endp;
8977 	int		len;
8978 	uint32_t	mss;
8979 	uchar_t		*up = (uchar_t *)tcph;
8980 	int		found = 0;
8981 	int32_t		sack_len;
8982 	tcp_seq		sack_begin, sack_end;
8983 	tcp_t		*tcp;
8984 
8985 	endp = up + TCP_HDR_LENGTH(tcph);
8986 	up += TCP_MIN_HEADER_LENGTH;
8987 	while (up < endp) {
8988 		len = endp - up;
8989 		switch (*up) {
8990 		case TCPOPT_EOL:
8991 			break;
8992 
8993 		case TCPOPT_NOP:
8994 			up++;
8995 			continue;
8996 
8997 		case TCPOPT_MAXSEG:
8998 			if (len < TCPOPT_MAXSEG_LEN ||
8999 			    up[1] != TCPOPT_MAXSEG_LEN)
9000 				break;
9001 
9002 			mss = BE16_TO_U16(up+2);
9003 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9004 			tcpopt->tcp_opt_mss = mss;
9005 			found |= TCP_OPT_MSS_PRESENT;
9006 
9007 			up += TCPOPT_MAXSEG_LEN;
9008 			continue;
9009 
9010 		case TCPOPT_WSCALE:
9011 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9012 				break;
9013 
9014 			if (up[2] > TCP_MAX_WINSHIFT)
9015 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9016 			else
9017 				tcpopt->tcp_opt_wscale = up[2];
9018 			found |= TCP_OPT_WSCALE_PRESENT;
9019 
9020 			up += TCPOPT_WS_LEN;
9021 			continue;
9022 
9023 		case TCPOPT_SACK_PERMITTED:
9024 			if (len < TCPOPT_SACK_OK_LEN ||
9025 			    up[1] != TCPOPT_SACK_OK_LEN)
9026 				break;
9027 			found |= TCP_OPT_SACK_OK_PRESENT;
9028 			up += TCPOPT_SACK_OK_LEN;
9029 			continue;
9030 
9031 		case TCPOPT_SACK:
9032 			if (len <= 2 || up[1] <= 2 || len < up[1])
9033 				break;
9034 
9035 			/* If TCP is not interested in SACK blks... */
9036 			if ((tcp = tcpopt->tcp) == NULL) {
9037 				up += up[1];
9038 				continue;
9039 			}
9040 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9041 			up += TCPOPT_HEADER_LEN;
9042 
9043 			/*
9044 			 * If the list is empty, allocate one and assume
9045 			 * nothing is sack'ed.
9046 			 */
9047 			ASSERT(tcp->tcp_sack_info != NULL);
9048 			if (tcp->tcp_notsack_list == NULL) {
9049 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9050 				    tcp->tcp_suna, tcp->tcp_snxt,
9051 				    &(tcp->tcp_num_notsack_blk),
9052 				    &(tcp->tcp_cnt_notsack_list));
9053 
9054 				/*
9055 				 * Make sure tcp_notsack_list is not NULL.
9056 				 * This happens when kmem_alloc(KM_NOSLEEP)
9057 				 * returns NULL.
9058 				 */
9059 				if (tcp->tcp_notsack_list == NULL) {
9060 					up += sack_len;
9061 					continue;
9062 				}
9063 				tcp->tcp_fack = tcp->tcp_suna;
9064 			}
9065 
9066 			while (sack_len > 0) {
9067 				if (up + 8 > endp) {
9068 					up = endp;
9069 					break;
9070 				}
9071 				sack_begin = BE32_TO_U32(up);
9072 				up += 4;
9073 				sack_end = BE32_TO_U32(up);
9074 				up += 4;
9075 				sack_len -= 8;
9076 				/*
9077 				 * Bounds checking.  Make sure the SACK
9078 				 * info is within tcp_suna and tcp_snxt.
9079 				 * If this SACK blk is out of bound, ignore
9080 				 * it but continue to parse the following
9081 				 * blks.
9082 				 */
9083 				if (SEQ_LEQ(sack_end, sack_begin) ||
9084 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9085 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9086 					continue;
9087 				}
9088 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9089 				    sack_begin, sack_end,
9090 				    &(tcp->tcp_num_notsack_blk),
9091 				    &(tcp->tcp_cnt_notsack_list));
9092 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9093 					tcp->tcp_fack = sack_end;
9094 				}
9095 			}
9096 			found |= TCP_OPT_SACK_PRESENT;
9097 			continue;
9098 
9099 		case TCPOPT_TSTAMP:
9100 			if (len < TCPOPT_TSTAMP_LEN ||
9101 			    up[1] != TCPOPT_TSTAMP_LEN)
9102 				break;
9103 
9104 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9105 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9106 
9107 			found |= TCP_OPT_TSTAMP_PRESENT;
9108 
9109 			up += TCPOPT_TSTAMP_LEN;
9110 			continue;
9111 
9112 		default:
9113 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9114 				break;
9115 			up += up[1];
9116 			continue;
9117 		}
9118 		break;
9119 	}
9120 	return (found);
9121 }
9122 
9123 /*
9124  * Set the mss associated with a particular tcp based on its current value,
9125  * and a new one passed in. Observe minimums and maximums, and reset
9126  * other state variables that we want to view as multiples of mss.
9127  *
9128  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9129  * highwater marks etc. need to be initialized or adjusted.
9130  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9131  *    packet arrives.
9132  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9133  *    ICMP6_PACKET_TOO_BIG arrives.
9134  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9135  *    to increase the MSS to use the extra bytes available.
9136  *
9137  * Callers except tcp_paws_check() ensure that they only reduce mss.
9138  */
9139 static void
9140 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9141 {
9142 	uint32_t	mss_max;
9143 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9144 
9145 	if (tcp->tcp_ipversion == IPV4_VERSION)
9146 		mss_max = tcps->tcps_mss_max_ipv4;
9147 	else
9148 		mss_max = tcps->tcps_mss_max_ipv6;
9149 
9150 	if (mss < tcps->tcps_mss_min)
9151 		mss = tcps->tcps_mss_min;
9152 	if (mss > mss_max)
9153 		mss = mss_max;
9154 	/*
9155 	 * Unless naglim has been set by our client to
9156 	 * a non-mss value, force naglim to track mss.
9157 	 * This can help to aggregate small writes.
9158 	 */
9159 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9160 		tcp->tcp_naglim = mss;
9161 	/*
9162 	 * TCP should be able to buffer at least 4 MSS data for obvious
9163 	 * performance reason.
9164 	 */
9165 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9166 		tcp->tcp_xmit_hiwater = mss << 2;
9167 
9168 	/*
9169 	 * Set the xmit_lowater to at least twice of MSS.
9170 	 */
9171 	if ((mss << 1) > tcp->tcp_xmit_lowater)
9172 		tcp->tcp_xmit_lowater = mss << 1;
9173 
9174 	if (do_ss) {
9175 		/*
9176 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9177 		 * changing due to a reduction in MTU, presumably as a
9178 		 * result of a new path component, reset cwnd to its
9179 		 * "initial" value, as a multiple of the new mss.
9180 		 */
9181 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9182 	} else {
9183 		/*
9184 		 * Called by tcp_paws_check(), the mss increased
9185 		 * marginally to allow use of space previously taken
9186 		 * by the timestamp option. It would be inappropriate
9187 		 * to apply slow start or tcp_init_cwnd values to
9188 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9189 		 */
9190 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9191 		tcp->tcp_cwnd_cnt = 0;
9192 	}
9193 	tcp->tcp_mss = mss;
9194 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9195 }
9196 
9197 /* For /dev/tcp aka AF_INET open */
9198 static int
9199 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9200 {
9201 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9202 }
9203 
9204 /* For /dev/tcp6 aka AF_INET6 open */
9205 static int
9206 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9207 {
9208 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9209 }
9210 
9211 static conn_t *
9212 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9213     boolean_t issocket, int *errorp)
9214 {
9215 	tcp_t		*tcp = NULL;
9216 	conn_t		*connp;
9217 	int		err;
9218 	zoneid_t	zoneid;
9219 	tcp_stack_t	*tcps;
9220 	squeue_t	*sqp;
9221 
9222 	ASSERT(errorp != NULL);
9223 	/*
9224 	 * Find the proper zoneid and netstack.
9225 	 */
9226 	/*
9227 	 * Special case for install: miniroot needs to be able to
9228 	 * access files via NFS as though it were always in the
9229 	 * global zone.
9230 	 */
9231 	if (credp == kcred && nfs_global_client_only != 0) {
9232 		zoneid = GLOBAL_ZONEID;
9233 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9234 		    netstack_tcp;
9235 		ASSERT(tcps != NULL);
9236 	} else {
9237 		netstack_t *ns;
9238 
9239 		ns = netstack_find_by_cred(credp);
9240 		ASSERT(ns != NULL);
9241 		tcps = ns->netstack_tcp;
9242 		ASSERT(tcps != NULL);
9243 
9244 		/*
9245 		 * For exclusive stacks we set the zoneid to zero
9246 		 * to make TCP operate as if in the global zone.
9247 		 */
9248 		if (tcps->tcps_netstack->netstack_stackid !=
9249 		    GLOBAL_NETSTACKID)
9250 			zoneid = GLOBAL_ZONEID;
9251 		else
9252 			zoneid = crgetzoneid(credp);
9253 	}
9254 	/*
9255 	 * For stackid zero this is done from strplumb.c, but
9256 	 * non-zero stackids are handled here.
9257 	 */
9258 	if (tcps->tcps_g_q == NULL &&
9259 	    tcps->tcps_netstack->netstack_stackid !=
9260 	    GLOBAL_NETSTACKID) {
9261 		tcp_g_q_setup(tcps);
9262 	}
9263 
9264 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9265 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9266 	/*
9267 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9268 	 * so we drop it by one.
9269 	 */
9270 	netstack_rele(tcps->tcps_netstack);
9271 	if (connp == NULL) {
9272 		*errorp = ENOSR;
9273 		return (NULL);
9274 	}
9275 	connp->conn_sqp = sqp;
9276 	connp->conn_initial_sqp = connp->conn_sqp;
9277 	tcp = connp->conn_tcp;
9278 
9279 	if (isv6) {
9280 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9281 		connp->conn_send = ip_output_v6;
9282 		connp->conn_af_isv6 = B_TRUE;
9283 		connp->conn_pkt_isv6 = B_TRUE;
9284 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9285 		tcp->tcp_ipversion = IPV6_VERSION;
9286 		tcp->tcp_family = AF_INET6;
9287 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9288 	} else {
9289 		connp->conn_flags |= IPCL_TCP4;
9290 		connp->conn_send = ip_output;
9291 		connp->conn_af_isv6 = B_FALSE;
9292 		connp->conn_pkt_isv6 = B_FALSE;
9293 		tcp->tcp_ipversion = IPV4_VERSION;
9294 		tcp->tcp_family = AF_INET;
9295 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9296 	}
9297 
9298 	/*
9299 	 * TCP keeps a copy of cred for cache locality reasons but
9300 	 * we put a reference only once. If connp->conn_cred
9301 	 * becomes invalid, tcp_cred should also be set to NULL.
9302 	 */
9303 	tcp->tcp_cred = connp->conn_cred = credp;
9304 	crhold(connp->conn_cred);
9305 	tcp->tcp_cpid = curproc->p_pid;
9306 	tcp->tcp_open_time = lbolt64;
9307 	connp->conn_zoneid = zoneid;
9308 	connp->conn_mlp_type = mlptSingle;
9309 	connp->conn_ulp_labeled = !is_system_labeled();
9310 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9311 	ASSERT(tcp->tcp_tcps == tcps);
9312 
9313 	/*
9314 	 * If the caller has the process-wide flag set, then default to MAC
9315 	 * exempt mode.  This allows read-down to unlabeled hosts.
9316 	 */
9317 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9318 		connp->conn_mac_exempt = B_TRUE;
9319 
9320 	connp->conn_dev = NULL;
9321 	if (issocket) {
9322 		connp->conn_flags |= IPCL_SOCKET;
9323 		tcp->tcp_issocket = 1;
9324 	}
9325 
9326 	/* Non-zero default values */
9327 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9328 
9329 	if (q == NULL) {
9330 		/*
9331 		 * Create a helper stream for non-STREAMS socket.
9332 		 */
9333 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9334 		if (err != 0) {
9335 			ip1dbg(("tcp_create_common: create of IP helper stream "
9336 			    "failed\n"));
9337 			CONN_DEC_REF(connp);
9338 			*errorp = err;
9339 			return (NULL);
9340 		}
9341 		q = connp->conn_rq;
9342 	}
9343 
9344 	SOCK_CONNID_INIT(tcp->tcp_connid);
9345 	err = tcp_init(tcp, q);
9346 	if (err != 0) {
9347 		CONN_DEC_REF(connp);
9348 		*errorp = err;
9349 		return (NULL);
9350 	}
9351 
9352 	return (connp);
9353 }
9354 
9355 static int
9356 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9357     boolean_t isv6)
9358 {
9359 	tcp_t		*tcp = NULL;
9360 	conn_t		*connp = NULL;
9361 	int		err;
9362 	vmem_t		*minor_arena = NULL;
9363 	dev_t		conn_dev;
9364 	boolean_t	issocket;
9365 
9366 	if (q->q_ptr != NULL)
9367 		return (0);
9368 
9369 	if (sflag == MODOPEN)
9370 		return (EINVAL);
9371 
9372 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9373 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9374 		minor_arena = ip_minor_arena_la;
9375 	} else {
9376 		/*
9377 		 * Either minor numbers in the large arena were exhausted
9378 		 * or a non socket application is doing the open.
9379 		 * Try to allocate from the small arena.
9380 		 */
9381 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9382 			return (EBUSY);
9383 		}
9384 		minor_arena = ip_minor_arena_sa;
9385 	}
9386 
9387 	ASSERT(minor_arena != NULL);
9388 
9389 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9390 
9391 	if (flag & SO_FALLBACK) {
9392 		/*
9393 		 * Non streams socket needs a stream to fallback to
9394 		 */
9395 		RD(q)->q_ptr = (void *)conn_dev;
9396 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9397 		WR(q)->q_ptr = (void *)minor_arena;
9398 		qprocson(q);
9399 		return (0);
9400 	} else if (flag & SO_ACCEPTOR) {
9401 		q->q_qinfo = &tcp_acceptor_rinit;
9402 		/*
9403 		 * the conn_dev and minor_arena will be subsequently used by
9404 		 * tcp_wput_accept() and tcp_tpi_close_accept() to figure out
9405 		 * the minor device number for this connection from the q_ptr.
9406 		 */
9407 		RD(q)->q_ptr = (void *)conn_dev;
9408 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9409 		WR(q)->q_ptr = (void *)minor_arena;
9410 		qprocson(q);
9411 		return (0);
9412 	}
9413 
9414 	issocket = flag & SO_SOCKSTR;
9415 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9416 
9417 	if (connp == NULL) {
9418 		inet_minor_free(minor_arena, conn_dev);
9419 		q->q_ptr = WR(q)->q_ptr = NULL;
9420 		return (err);
9421 	}
9422 
9423 	q->q_ptr = WR(q)->q_ptr = connp;
9424 
9425 	connp->conn_dev = conn_dev;
9426 	connp->conn_minor_arena = minor_arena;
9427 
9428 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9429 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9430 
9431 	tcp = connp->conn_tcp;
9432 
9433 	if (issocket) {
9434 		WR(q)->q_qinfo = &tcp_sock_winit;
9435 	} else {
9436 #ifdef  _ILP32
9437 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9438 #else
9439 		tcp->tcp_acceptor_id = conn_dev;
9440 #endif  /* _ILP32 */
9441 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9442 	}
9443 
9444 	/*
9445 	 * Put the ref for TCP. Ref for IP was already put
9446 	 * by ipcl_conn_create. Also Make the conn_t globally
9447 	 * visible to walkers
9448 	 */
9449 	mutex_enter(&connp->conn_lock);
9450 	CONN_INC_REF_LOCKED(connp);
9451 	ASSERT(connp->conn_ref == 2);
9452 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9453 	mutex_exit(&connp->conn_lock);
9454 
9455 	qprocson(q);
9456 	return (0);
9457 }
9458 
9459 /*
9460  * Some TCP options can be "set" by requesting them in the option
9461  * buffer. This is needed for XTI feature test though we do not
9462  * allow it in general. We interpret that this mechanism is more
9463  * applicable to OSI protocols and need not be allowed in general.
9464  * This routine filters out options for which it is not allowed (most)
9465  * and lets through those (few) for which it is. [ The XTI interface
9466  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9467  * ever implemented will have to be allowed here ].
9468  */
9469 static boolean_t
9470 tcp_allow_connopt_set(int level, int name)
9471 {
9472 
9473 	switch (level) {
9474 	case IPPROTO_TCP:
9475 		switch (name) {
9476 		case TCP_NODELAY:
9477 			return (B_TRUE);
9478 		default:
9479 			return (B_FALSE);
9480 		}
9481 		/*NOTREACHED*/
9482 	default:
9483 		return (B_FALSE);
9484 	}
9485 	/*NOTREACHED*/
9486 }
9487 
9488 /*
9489  * this routine gets default values of certain options whose default
9490  * values are maintained by protocol specific code
9491  */
9492 /* ARGSUSED */
9493 int
9494 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9495 {
9496 	int32_t	*i1 = (int32_t *)ptr;
9497 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9498 
9499 	switch (level) {
9500 	case IPPROTO_TCP:
9501 		switch (name) {
9502 		case TCP_NOTIFY_THRESHOLD:
9503 			*i1 = tcps->tcps_ip_notify_interval;
9504 			break;
9505 		case TCP_ABORT_THRESHOLD:
9506 			*i1 = tcps->tcps_ip_abort_interval;
9507 			break;
9508 		case TCP_CONN_NOTIFY_THRESHOLD:
9509 			*i1 = tcps->tcps_ip_notify_cinterval;
9510 			break;
9511 		case TCP_CONN_ABORT_THRESHOLD:
9512 			*i1 = tcps->tcps_ip_abort_cinterval;
9513 			break;
9514 		default:
9515 			return (-1);
9516 		}
9517 		break;
9518 	case IPPROTO_IP:
9519 		switch (name) {
9520 		case IP_TTL:
9521 			*i1 = tcps->tcps_ipv4_ttl;
9522 			break;
9523 		default:
9524 			return (-1);
9525 		}
9526 		break;
9527 	case IPPROTO_IPV6:
9528 		switch (name) {
9529 		case IPV6_UNICAST_HOPS:
9530 			*i1 = tcps->tcps_ipv6_hoplimit;
9531 			break;
9532 		default:
9533 			return (-1);
9534 		}
9535 		break;
9536 	default:
9537 		return (-1);
9538 	}
9539 	return (sizeof (int));
9540 }
9541 
9542 static int
9543 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9544 {
9545 	int		*i1 = (int *)ptr;
9546 	tcp_t		*tcp = connp->conn_tcp;
9547 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9548 
9549 	switch (level) {
9550 	case SOL_SOCKET:
9551 		switch (name) {
9552 		case SO_LINGER:	{
9553 			struct linger *lgr = (struct linger *)ptr;
9554 
9555 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9556 			lgr->l_linger = tcp->tcp_lingertime;
9557 			}
9558 			return (sizeof (struct linger));
9559 		case SO_DEBUG:
9560 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9561 			break;
9562 		case SO_KEEPALIVE:
9563 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9564 			break;
9565 		case SO_DONTROUTE:
9566 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9567 			break;
9568 		case SO_USELOOPBACK:
9569 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9570 			break;
9571 		case SO_BROADCAST:
9572 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9573 			break;
9574 		case SO_REUSEADDR:
9575 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9576 			break;
9577 		case SO_OOBINLINE:
9578 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9579 			break;
9580 		case SO_DGRAM_ERRIND:
9581 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9582 			break;
9583 		case SO_TYPE:
9584 			*i1 = SOCK_STREAM;
9585 			break;
9586 		case SO_SNDBUF:
9587 			*i1 = tcp->tcp_xmit_hiwater;
9588 			break;
9589 		case SO_RCVBUF:
9590 			*i1 = tcp->tcp_recv_hiwater;
9591 			break;
9592 		case SO_SND_COPYAVOID:
9593 			*i1 = tcp->tcp_snd_zcopy_on ?
9594 			    SO_SND_COPYAVOID : 0;
9595 			break;
9596 		case SO_ALLZONES:
9597 			*i1 = connp->conn_allzones ? 1 : 0;
9598 			break;
9599 		case SO_ANON_MLP:
9600 			*i1 = connp->conn_anon_mlp;
9601 			break;
9602 		case SO_MAC_EXEMPT:
9603 			*i1 = connp->conn_mac_exempt;
9604 			break;
9605 		case SO_EXCLBIND:
9606 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9607 			break;
9608 		case SO_PROTOTYPE:
9609 			*i1 = IPPROTO_TCP;
9610 			break;
9611 		case SO_DOMAIN:
9612 			*i1 = tcp->tcp_family;
9613 			break;
9614 		case SO_ACCEPTCONN:
9615 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9616 		default:
9617 			return (-1);
9618 		}
9619 		break;
9620 	case IPPROTO_TCP:
9621 		switch (name) {
9622 		case TCP_NODELAY:
9623 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9624 			break;
9625 		case TCP_MAXSEG:
9626 			*i1 = tcp->tcp_mss;
9627 			break;
9628 		case TCP_NOTIFY_THRESHOLD:
9629 			*i1 = (int)tcp->tcp_first_timer_threshold;
9630 			break;
9631 		case TCP_ABORT_THRESHOLD:
9632 			*i1 = tcp->tcp_second_timer_threshold;
9633 			break;
9634 		case TCP_CONN_NOTIFY_THRESHOLD:
9635 			*i1 = tcp->tcp_first_ctimer_threshold;
9636 			break;
9637 		case TCP_CONN_ABORT_THRESHOLD:
9638 			*i1 = tcp->tcp_second_ctimer_threshold;
9639 			break;
9640 		case TCP_RECVDSTADDR:
9641 			*i1 = tcp->tcp_recvdstaddr;
9642 			break;
9643 		case TCP_ANONPRIVBIND:
9644 			*i1 = tcp->tcp_anon_priv_bind;
9645 			break;
9646 		case TCP_EXCLBIND:
9647 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9648 			break;
9649 		case TCP_INIT_CWND:
9650 			*i1 = tcp->tcp_init_cwnd;
9651 			break;
9652 		case TCP_KEEPALIVE_THRESHOLD:
9653 			*i1 = tcp->tcp_ka_interval;
9654 			break;
9655 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9656 			*i1 = tcp->tcp_ka_abort_thres;
9657 			break;
9658 		case TCP_CORK:
9659 			*i1 = tcp->tcp_cork;
9660 			break;
9661 		default:
9662 			return (-1);
9663 		}
9664 		break;
9665 	case IPPROTO_IP:
9666 		if (tcp->tcp_family != AF_INET)
9667 			return (-1);
9668 		switch (name) {
9669 		case IP_OPTIONS:
9670 		case T_IP_OPTIONS: {
9671 			/*
9672 			 * This is compatible with BSD in that in only return
9673 			 * the reverse source route with the final destination
9674 			 * as the last entry. The first 4 bytes of the option
9675 			 * will contain the final destination.
9676 			 */
9677 			int	opt_len;
9678 
9679 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9680 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9681 			ASSERT(opt_len >= 0);
9682 			/* Caller ensures enough space */
9683 			if (opt_len > 0) {
9684 				/*
9685 				 * TODO: Do we have to handle getsockopt on an
9686 				 * initiator as well?
9687 				 */
9688 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9689 			}
9690 			return (0);
9691 			}
9692 		case IP_TOS:
9693 		case T_IP_TOS:
9694 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9695 			break;
9696 		case IP_TTL:
9697 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9698 			break;
9699 		case IP_NEXTHOP:
9700 			/* Handled at IP level */
9701 			return (-EINVAL);
9702 		default:
9703 			return (-1);
9704 		}
9705 		break;
9706 	case IPPROTO_IPV6:
9707 		/*
9708 		 * IPPROTO_IPV6 options are only supported for sockets
9709 		 * that are using IPv6 on the wire.
9710 		 */
9711 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9712 			return (-1);
9713 		}
9714 		switch (name) {
9715 		case IPV6_UNICAST_HOPS:
9716 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9717 			break;	/* goto sizeof (int) option return */
9718 		case IPV6_BOUND_IF:
9719 			/* Zero if not set */
9720 			*i1 = tcp->tcp_bound_if;
9721 			break;	/* goto sizeof (int) option return */
9722 		case IPV6_RECVPKTINFO:
9723 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9724 				*i1 = 1;
9725 			else
9726 				*i1 = 0;
9727 			break;	/* goto sizeof (int) option return */
9728 		case IPV6_RECVTCLASS:
9729 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9730 				*i1 = 1;
9731 			else
9732 				*i1 = 0;
9733 			break;	/* goto sizeof (int) option return */
9734 		case IPV6_RECVHOPLIMIT:
9735 			if (tcp->tcp_ipv6_recvancillary &
9736 			    TCP_IPV6_RECVHOPLIMIT)
9737 				*i1 = 1;
9738 			else
9739 				*i1 = 0;
9740 			break;	/* goto sizeof (int) option return */
9741 		case IPV6_RECVHOPOPTS:
9742 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9743 				*i1 = 1;
9744 			else
9745 				*i1 = 0;
9746 			break;	/* goto sizeof (int) option return */
9747 		case IPV6_RECVDSTOPTS:
9748 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9749 				*i1 = 1;
9750 			else
9751 				*i1 = 0;
9752 			break;	/* goto sizeof (int) option return */
9753 		case _OLD_IPV6_RECVDSTOPTS:
9754 			if (tcp->tcp_ipv6_recvancillary &
9755 			    TCP_OLD_IPV6_RECVDSTOPTS)
9756 				*i1 = 1;
9757 			else
9758 				*i1 = 0;
9759 			break;	/* goto sizeof (int) option return */
9760 		case IPV6_RECVRTHDR:
9761 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9762 				*i1 = 1;
9763 			else
9764 				*i1 = 0;
9765 			break;	/* goto sizeof (int) option return */
9766 		case IPV6_RECVRTHDRDSTOPTS:
9767 			if (tcp->tcp_ipv6_recvancillary &
9768 			    TCP_IPV6_RECVRTDSTOPTS)
9769 				*i1 = 1;
9770 			else
9771 				*i1 = 0;
9772 			break;	/* goto sizeof (int) option return */
9773 		case IPV6_PKTINFO: {
9774 			/* XXX assumes that caller has room for max size! */
9775 			struct in6_pktinfo *pkti;
9776 
9777 			pkti = (struct in6_pktinfo *)ptr;
9778 			if (ipp->ipp_fields & IPPF_IFINDEX)
9779 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9780 			else
9781 				pkti->ipi6_ifindex = 0;
9782 			if (ipp->ipp_fields & IPPF_ADDR)
9783 				pkti->ipi6_addr = ipp->ipp_addr;
9784 			else
9785 				pkti->ipi6_addr = ipv6_all_zeros;
9786 			return (sizeof (struct in6_pktinfo));
9787 		}
9788 		case IPV6_TCLASS:
9789 			if (ipp->ipp_fields & IPPF_TCLASS)
9790 				*i1 = ipp->ipp_tclass;
9791 			else
9792 				*i1 = IPV6_FLOW_TCLASS(
9793 				    IPV6_DEFAULT_VERS_AND_FLOW);
9794 			break;	/* goto sizeof (int) option return */
9795 		case IPV6_NEXTHOP: {
9796 			sin6_t *sin6 = (sin6_t *)ptr;
9797 
9798 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9799 				return (0);
9800 			*sin6 = sin6_null;
9801 			sin6->sin6_family = AF_INET6;
9802 			sin6->sin6_addr = ipp->ipp_nexthop;
9803 			return (sizeof (sin6_t));
9804 		}
9805 		case IPV6_HOPOPTS:
9806 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9807 				return (0);
9808 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9809 				return (0);
9810 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9811 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9812 			if (tcp->tcp_label_len > 0) {
9813 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9814 				ptr[1] = (ipp->ipp_hopoptslen -
9815 				    tcp->tcp_label_len + 7) / 8 - 1;
9816 			}
9817 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9818 		case IPV6_RTHDRDSTOPTS:
9819 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9820 				return (0);
9821 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9822 			return (ipp->ipp_rtdstoptslen);
9823 		case IPV6_RTHDR:
9824 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9825 				return (0);
9826 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9827 			return (ipp->ipp_rthdrlen);
9828 		case IPV6_DSTOPTS:
9829 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9830 				return (0);
9831 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9832 			return (ipp->ipp_dstoptslen);
9833 		case IPV6_SRC_PREFERENCES:
9834 			return (ip6_get_src_preferences(connp,
9835 			    (uint32_t *)ptr));
9836 		case IPV6_PATHMTU: {
9837 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9838 
9839 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9840 				return (-1);
9841 
9842 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9843 			    connp->conn_fport, mtuinfo,
9844 			    connp->conn_netstack));
9845 		}
9846 		default:
9847 			return (-1);
9848 		}
9849 		break;
9850 	default:
9851 		return (-1);
9852 	}
9853 	return (sizeof (int));
9854 }
9855 
9856 /*
9857  * TCP routine to get the values of options.
9858  */
9859 int
9860 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9861 {
9862 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9863 }
9864 
9865 /* returns UNIX error, the optlen is a value-result arg */
9866 int
9867 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9868     void *optvalp, socklen_t *optlen, cred_t *cr)
9869 {
9870 	conn_t		*connp = (conn_t *)proto_handle;
9871 	squeue_t	*sqp = connp->conn_sqp;
9872 	int		error;
9873 	t_uscalar_t	max_optbuf_len;
9874 	void		*optvalp_buf;
9875 	int		len;
9876 
9877 	ASSERT(connp->conn_upper_handle != NULL);
9878 
9879 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9880 	    tcp_opt_obj.odb_opt_des_arr,
9881 	    tcp_opt_obj.odb_opt_arr_cnt,
9882 	    tcp_opt_obj.odb_topmost_tpiprovider,
9883 	    B_FALSE, B_TRUE, cr);
9884 	if (error != 0) {
9885 		if (error < 0) {
9886 			error = proto_tlitosyserr(-error);
9887 		}
9888 		return (error);
9889 	}
9890 
9891 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9892 
9893 	error = squeue_synch_enter(sqp, connp, NULL);
9894 	if (error == ENOMEM) {
9895 		return (ENOMEM);
9896 	}
9897 
9898 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9899 	squeue_synch_exit(sqp, connp);
9900 
9901 	if (len < 0) {
9902 		/*
9903 		 * Pass on to IP
9904 		 */
9905 		kmem_free(optvalp_buf, max_optbuf_len);
9906 		return (ip_get_options(connp, level, option_name,
9907 		    optvalp, optlen, cr));
9908 	} else {
9909 		/*
9910 		 * update optlen and copy option value
9911 		 */
9912 		t_uscalar_t size = MIN(len, *optlen);
9913 		bcopy(optvalp_buf, optvalp, size);
9914 		bcopy(&size, optlen, sizeof (size));
9915 
9916 		kmem_free(optvalp_buf, max_optbuf_len);
9917 		return (0);
9918 	}
9919 }
9920 
9921 /*
9922  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9923  * Parameters are assumed to be verified by the caller.
9924  */
9925 /* ARGSUSED */
9926 int
9927 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9928     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9929     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9930 {
9931 	tcp_t	*tcp = connp->conn_tcp;
9932 	int	*i1 = (int *)invalp;
9933 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9934 	boolean_t checkonly;
9935 	int	reterr;
9936 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9937 
9938 	switch (optset_context) {
9939 	case SETFN_OPTCOM_CHECKONLY:
9940 		checkonly = B_TRUE;
9941 		/*
9942 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9943 		 * inlen != 0 implies value supplied and
9944 		 * 	we have to "pretend" to set it.
9945 		 * inlen == 0 implies that there is no
9946 		 * 	value part in T_CHECK request and just validation
9947 		 * done elsewhere should be enough, we just return here.
9948 		 */
9949 		if (inlen == 0) {
9950 			*outlenp = 0;
9951 			return (0);
9952 		}
9953 		break;
9954 	case SETFN_OPTCOM_NEGOTIATE:
9955 		checkonly = B_FALSE;
9956 		break;
9957 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9958 	case SETFN_CONN_NEGOTIATE:
9959 		checkonly = B_FALSE;
9960 		/*
9961 		 * Negotiating local and "association-related" options
9962 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9963 		 * primitives is allowed by XTI, but we choose
9964 		 * to not implement this style negotiation for Internet
9965 		 * protocols (We interpret it is a must for OSI world but
9966 		 * optional for Internet protocols) for all options.
9967 		 * [ Will do only for the few options that enable test
9968 		 * suites that our XTI implementation of this feature
9969 		 * works for transports that do allow it ]
9970 		 */
9971 		if (!tcp_allow_connopt_set(level, name)) {
9972 			*outlenp = 0;
9973 			return (EINVAL);
9974 		}
9975 		break;
9976 	default:
9977 		/*
9978 		 * We should never get here
9979 		 */
9980 		*outlenp = 0;
9981 		return (EINVAL);
9982 	}
9983 
9984 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9985 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9986 
9987 	/*
9988 	 * For TCP, we should have no ancillary data sent down
9989 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9990 	 * has to be zero.
9991 	 */
9992 	ASSERT(thisdg_attrs == NULL);
9993 
9994 	/*
9995 	 * For fixed length options, no sanity check
9996 	 * of passed in length is done. It is assumed *_optcom_req()
9997 	 * routines do the right thing.
9998 	 */
9999 	switch (level) {
10000 	case SOL_SOCKET:
10001 		switch (name) {
10002 		case SO_LINGER: {
10003 			struct linger *lgr = (struct linger *)invalp;
10004 
10005 			if (!checkonly) {
10006 				if (lgr->l_onoff) {
10007 					tcp->tcp_linger = 1;
10008 					tcp->tcp_lingertime = lgr->l_linger;
10009 				} else {
10010 					tcp->tcp_linger = 0;
10011 					tcp->tcp_lingertime = 0;
10012 				}
10013 				/* struct copy */
10014 				*(struct linger *)outvalp = *lgr;
10015 			} else {
10016 				if (!lgr->l_onoff) {
10017 					((struct linger *)
10018 					    outvalp)->l_onoff = 0;
10019 					((struct linger *)
10020 					    outvalp)->l_linger = 0;
10021 				} else {
10022 					/* struct copy */
10023 					*(struct linger *)outvalp = *lgr;
10024 				}
10025 			}
10026 			*outlenp = sizeof (struct linger);
10027 			return (0);
10028 		}
10029 		case SO_DEBUG:
10030 			if (!checkonly)
10031 				tcp->tcp_debug = onoff;
10032 			break;
10033 		case SO_KEEPALIVE:
10034 			if (checkonly) {
10035 				/* check only case */
10036 				break;
10037 			}
10038 
10039 			if (!onoff) {
10040 				if (tcp->tcp_ka_enabled) {
10041 					if (tcp->tcp_ka_tid != 0) {
10042 						(void) TCP_TIMER_CANCEL(tcp,
10043 						    tcp->tcp_ka_tid);
10044 						tcp->tcp_ka_tid = 0;
10045 					}
10046 					tcp->tcp_ka_enabled = 0;
10047 				}
10048 				break;
10049 			}
10050 			if (!tcp->tcp_ka_enabled) {
10051 				/* Crank up the keepalive timer */
10052 				tcp->tcp_ka_last_intrvl = 0;
10053 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10054 				    tcp_keepalive_killer,
10055 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10056 				tcp->tcp_ka_enabled = 1;
10057 			}
10058 			break;
10059 		case SO_DONTROUTE:
10060 			/*
10061 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10062 			 * only of interest to IP.  We track them here only so
10063 			 * that we can report their current value.
10064 			 */
10065 			if (!checkonly) {
10066 				tcp->tcp_dontroute = onoff;
10067 				tcp->tcp_connp->conn_dontroute = onoff;
10068 			}
10069 			break;
10070 		case SO_USELOOPBACK:
10071 			if (!checkonly) {
10072 				tcp->tcp_useloopback = onoff;
10073 				tcp->tcp_connp->conn_loopback = onoff;
10074 			}
10075 			break;
10076 		case SO_BROADCAST:
10077 			if (!checkonly) {
10078 				tcp->tcp_broadcast = onoff;
10079 				tcp->tcp_connp->conn_broadcast = onoff;
10080 			}
10081 			break;
10082 		case SO_REUSEADDR:
10083 			if (!checkonly) {
10084 				tcp->tcp_reuseaddr = onoff;
10085 				tcp->tcp_connp->conn_reuseaddr = onoff;
10086 			}
10087 			break;
10088 		case SO_OOBINLINE:
10089 			if (!checkonly) {
10090 				tcp->tcp_oobinline = onoff;
10091 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10092 					proto_set_rx_oob_opt(connp, onoff);
10093 			}
10094 			break;
10095 		case SO_DGRAM_ERRIND:
10096 			if (!checkonly)
10097 				tcp->tcp_dgram_errind = onoff;
10098 			break;
10099 		case SO_SNDBUF: {
10100 			if (*i1 > tcps->tcps_max_buf) {
10101 				*outlenp = 0;
10102 				return (ENOBUFS);
10103 			}
10104 			if (checkonly)
10105 				break;
10106 
10107 			tcp->tcp_xmit_hiwater = *i1;
10108 			if (tcps->tcps_snd_lowat_fraction != 0)
10109 				tcp->tcp_xmit_lowater =
10110 				    tcp->tcp_xmit_hiwater /
10111 				    tcps->tcps_snd_lowat_fraction;
10112 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10113 			/*
10114 			 * If we are flow-controlled, recheck the condition.
10115 			 * There are apps that increase SO_SNDBUF size when
10116 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10117 			 * control condition to be lifted right away.
10118 			 */
10119 			mutex_enter(&tcp->tcp_non_sq_lock);
10120 			if (tcp->tcp_flow_stopped &&
10121 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10122 				tcp_clrqfull(tcp);
10123 			}
10124 			mutex_exit(&tcp->tcp_non_sq_lock);
10125 			break;
10126 		}
10127 		case SO_RCVBUF:
10128 			if (*i1 > tcps->tcps_max_buf) {
10129 				*outlenp = 0;
10130 				return (ENOBUFS);
10131 			}
10132 			/* Silently ignore zero */
10133 			if (!checkonly && *i1 != 0) {
10134 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10135 				(void) tcp_rwnd_set(tcp, *i1);
10136 			}
10137 			/*
10138 			 * XXX should we return the rwnd here
10139 			 * and tcp_opt_get ?
10140 			 */
10141 			break;
10142 		case SO_SND_COPYAVOID:
10143 			if (!checkonly) {
10144 				/* we only allow enable at most once for now */
10145 				if (tcp->tcp_loopback ||
10146 				    (tcp->tcp_kssl_ctx != NULL) ||
10147 				    (!tcp->tcp_snd_zcopy_aware &&
10148 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10149 					*outlenp = 0;
10150 					return (EOPNOTSUPP);
10151 				}
10152 				tcp->tcp_snd_zcopy_aware = 1;
10153 			}
10154 			break;
10155 		case SO_RCVTIMEO:
10156 		case SO_SNDTIMEO:
10157 			/*
10158 			 * Pass these two options in order for third part
10159 			 * protocol usage. Here just return directly.
10160 			 */
10161 			return (0);
10162 		case SO_ALLZONES:
10163 			/* Pass option along to IP level for handling */
10164 			return (-EINVAL);
10165 		case SO_ANON_MLP:
10166 			/* Pass option along to IP level for handling */
10167 			return (-EINVAL);
10168 		case SO_MAC_EXEMPT:
10169 			/* Pass option along to IP level for handling */
10170 			return (-EINVAL);
10171 		case SO_EXCLBIND:
10172 			if (!checkonly)
10173 				tcp->tcp_exclbind = onoff;
10174 			break;
10175 		default:
10176 			*outlenp = 0;
10177 			return (EINVAL);
10178 		}
10179 		break;
10180 	case IPPROTO_TCP:
10181 		switch (name) {
10182 		case TCP_NODELAY:
10183 			if (!checkonly)
10184 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10185 			break;
10186 		case TCP_NOTIFY_THRESHOLD:
10187 			if (!checkonly)
10188 				tcp->tcp_first_timer_threshold = *i1;
10189 			break;
10190 		case TCP_ABORT_THRESHOLD:
10191 			if (!checkonly)
10192 				tcp->tcp_second_timer_threshold = *i1;
10193 			break;
10194 		case TCP_CONN_NOTIFY_THRESHOLD:
10195 			if (!checkonly)
10196 				tcp->tcp_first_ctimer_threshold = *i1;
10197 			break;
10198 		case TCP_CONN_ABORT_THRESHOLD:
10199 			if (!checkonly)
10200 				tcp->tcp_second_ctimer_threshold = *i1;
10201 			break;
10202 		case TCP_RECVDSTADDR:
10203 			if (tcp->tcp_state > TCPS_LISTEN)
10204 				return (EOPNOTSUPP);
10205 			if (!checkonly)
10206 				tcp->tcp_recvdstaddr = onoff;
10207 			break;
10208 		case TCP_ANONPRIVBIND:
10209 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10210 			    IPPROTO_TCP)) != 0) {
10211 				*outlenp = 0;
10212 				return (reterr);
10213 			}
10214 			if (!checkonly) {
10215 				tcp->tcp_anon_priv_bind = onoff;
10216 			}
10217 			break;
10218 		case TCP_EXCLBIND:
10219 			if (!checkonly)
10220 				tcp->tcp_exclbind = onoff;
10221 			break;	/* goto sizeof (int) option return */
10222 		case TCP_INIT_CWND: {
10223 			uint32_t init_cwnd = *((uint32_t *)invalp);
10224 
10225 			if (checkonly)
10226 				break;
10227 
10228 			/*
10229 			 * Only allow socket with network configuration
10230 			 * privilege to set the initial cwnd to be larger
10231 			 * than allowed by RFC 3390.
10232 			 */
10233 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10234 				tcp->tcp_init_cwnd = init_cwnd;
10235 				break;
10236 			}
10237 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10238 				*outlenp = 0;
10239 				return (reterr);
10240 			}
10241 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10242 				*outlenp = 0;
10243 				return (EINVAL);
10244 			}
10245 			tcp->tcp_init_cwnd = init_cwnd;
10246 			break;
10247 		}
10248 		case TCP_KEEPALIVE_THRESHOLD:
10249 			if (checkonly)
10250 				break;
10251 
10252 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10253 			    *i1 > tcps->tcps_keepalive_interval_high) {
10254 				*outlenp = 0;
10255 				return (EINVAL);
10256 			}
10257 			if (*i1 != tcp->tcp_ka_interval) {
10258 				tcp->tcp_ka_interval = *i1;
10259 				/*
10260 				 * Check if we need to restart the
10261 				 * keepalive timer.
10262 				 */
10263 				if (tcp->tcp_ka_tid != 0) {
10264 					ASSERT(tcp->tcp_ka_enabled);
10265 					(void) TCP_TIMER_CANCEL(tcp,
10266 					    tcp->tcp_ka_tid);
10267 					tcp->tcp_ka_last_intrvl = 0;
10268 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10269 					    tcp_keepalive_killer,
10270 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10271 				}
10272 			}
10273 			break;
10274 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10275 			if (!checkonly) {
10276 				if (*i1 <
10277 				    tcps->tcps_keepalive_abort_interval_low ||
10278 				    *i1 >
10279 				    tcps->tcps_keepalive_abort_interval_high) {
10280 					*outlenp = 0;
10281 					return (EINVAL);
10282 				}
10283 				tcp->tcp_ka_abort_thres = *i1;
10284 			}
10285 			break;
10286 		case TCP_CORK:
10287 			if (!checkonly) {
10288 				/*
10289 				 * if tcp->tcp_cork was set and is now
10290 				 * being unset, we have to make sure that
10291 				 * the remaining data gets sent out. Also
10292 				 * unset tcp->tcp_cork so that tcp_wput_data()
10293 				 * can send data even if it is less than mss
10294 				 */
10295 				if (tcp->tcp_cork && onoff == 0 &&
10296 				    tcp->tcp_unsent > 0) {
10297 					tcp->tcp_cork = B_FALSE;
10298 					tcp_wput_data(tcp, NULL, B_FALSE);
10299 				}
10300 				tcp->tcp_cork = onoff;
10301 			}
10302 			break;
10303 		default:
10304 			*outlenp = 0;
10305 			return (EINVAL);
10306 		}
10307 		break;
10308 	case IPPROTO_IP:
10309 		if (tcp->tcp_family != AF_INET) {
10310 			*outlenp = 0;
10311 			return (ENOPROTOOPT);
10312 		}
10313 		switch (name) {
10314 		case IP_OPTIONS:
10315 		case T_IP_OPTIONS:
10316 			reterr = tcp_opt_set_header(tcp, checkonly,
10317 			    invalp, inlen);
10318 			if (reterr) {
10319 				*outlenp = 0;
10320 				return (reterr);
10321 			}
10322 			/* OK return - copy input buffer into output buffer */
10323 			if (invalp != outvalp) {
10324 				/* don't trust bcopy for identical src/dst */
10325 				bcopy(invalp, outvalp, inlen);
10326 			}
10327 			*outlenp = inlen;
10328 			return (0);
10329 		case IP_TOS:
10330 		case T_IP_TOS:
10331 			if (!checkonly) {
10332 				tcp->tcp_ipha->ipha_type_of_service =
10333 				    (uchar_t)*i1;
10334 				tcp->tcp_tos = (uchar_t)*i1;
10335 			}
10336 			break;
10337 		case IP_TTL:
10338 			if (!checkonly) {
10339 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10340 				tcp->tcp_ttl = (uchar_t)*i1;
10341 			}
10342 			break;
10343 		case IP_BOUND_IF:
10344 		case IP_NEXTHOP:
10345 			/* Handled at the IP level */
10346 			return (-EINVAL);
10347 		case IP_SEC_OPT:
10348 			/*
10349 			 * We should not allow policy setting after
10350 			 * we start listening for connections.
10351 			 */
10352 			if (tcp->tcp_state == TCPS_LISTEN) {
10353 				return (EINVAL);
10354 			} else {
10355 				/* Handled at the IP level */
10356 				return (-EINVAL);
10357 			}
10358 		default:
10359 			*outlenp = 0;
10360 			return (EINVAL);
10361 		}
10362 		break;
10363 	case IPPROTO_IPV6: {
10364 		ip6_pkt_t		*ipp;
10365 
10366 		/*
10367 		 * IPPROTO_IPV6 options are only supported for sockets
10368 		 * that are using IPv6 on the wire.
10369 		 */
10370 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10371 			*outlenp = 0;
10372 			return (ENOPROTOOPT);
10373 		}
10374 		/*
10375 		 * Only sticky options; no ancillary data
10376 		 */
10377 		ipp = &tcp->tcp_sticky_ipp;
10378 
10379 		switch (name) {
10380 		case IPV6_UNICAST_HOPS:
10381 			/* -1 means use default */
10382 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10383 				*outlenp = 0;
10384 				return (EINVAL);
10385 			}
10386 			if (!checkonly) {
10387 				if (*i1 == -1) {
10388 					tcp->tcp_ip6h->ip6_hops =
10389 					    ipp->ipp_unicast_hops =
10390 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10391 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10392 					/* Pass modified value to IP. */
10393 					*i1 = tcp->tcp_ip6h->ip6_hops;
10394 				} else {
10395 					tcp->tcp_ip6h->ip6_hops =
10396 					    ipp->ipp_unicast_hops =
10397 					    (uint8_t)*i1;
10398 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10399 				}
10400 				reterr = tcp_build_hdrs(tcp);
10401 				if (reterr != 0)
10402 					return (reterr);
10403 			}
10404 			break;
10405 		case IPV6_BOUND_IF:
10406 			if (!checkonly) {
10407 				tcp->tcp_bound_if = *i1;
10408 				PASS_OPT_TO_IP(connp);
10409 			}
10410 			break;
10411 		/*
10412 		 * Set boolean switches for ancillary data delivery
10413 		 */
10414 		case IPV6_RECVPKTINFO:
10415 			if (!checkonly) {
10416 				if (onoff)
10417 					tcp->tcp_ipv6_recvancillary |=
10418 					    TCP_IPV6_RECVPKTINFO;
10419 				else
10420 					tcp->tcp_ipv6_recvancillary &=
10421 					    ~TCP_IPV6_RECVPKTINFO;
10422 				/* Force it to be sent up with the next msg */
10423 				tcp->tcp_recvifindex = 0;
10424 				PASS_OPT_TO_IP(connp);
10425 			}
10426 			break;
10427 		case IPV6_RECVTCLASS:
10428 			if (!checkonly) {
10429 				if (onoff)
10430 					tcp->tcp_ipv6_recvancillary |=
10431 					    TCP_IPV6_RECVTCLASS;
10432 				else
10433 					tcp->tcp_ipv6_recvancillary &=
10434 					    ~TCP_IPV6_RECVTCLASS;
10435 				PASS_OPT_TO_IP(connp);
10436 			}
10437 			break;
10438 		case IPV6_RECVHOPLIMIT:
10439 			if (!checkonly) {
10440 				if (onoff)
10441 					tcp->tcp_ipv6_recvancillary |=
10442 					    TCP_IPV6_RECVHOPLIMIT;
10443 				else
10444 					tcp->tcp_ipv6_recvancillary &=
10445 					    ~TCP_IPV6_RECVHOPLIMIT;
10446 				/* Force it to be sent up with the next msg */
10447 				tcp->tcp_recvhops = 0xffffffffU;
10448 				PASS_OPT_TO_IP(connp);
10449 			}
10450 			break;
10451 		case IPV6_RECVHOPOPTS:
10452 			if (!checkonly) {
10453 				if (onoff)
10454 					tcp->tcp_ipv6_recvancillary |=
10455 					    TCP_IPV6_RECVHOPOPTS;
10456 				else
10457 					tcp->tcp_ipv6_recvancillary &=
10458 					    ~TCP_IPV6_RECVHOPOPTS;
10459 				PASS_OPT_TO_IP(connp);
10460 			}
10461 			break;
10462 		case IPV6_RECVDSTOPTS:
10463 			if (!checkonly) {
10464 				if (onoff)
10465 					tcp->tcp_ipv6_recvancillary |=
10466 					    TCP_IPV6_RECVDSTOPTS;
10467 				else
10468 					tcp->tcp_ipv6_recvancillary &=
10469 					    ~TCP_IPV6_RECVDSTOPTS;
10470 				PASS_OPT_TO_IP(connp);
10471 			}
10472 			break;
10473 		case _OLD_IPV6_RECVDSTOPTS:
10474 			if (!checkonly) {
10475 				if (onoff)
10476 					tcp->tcp_ipv6_recvancillary |=
10477 					    TCP_OLD_IPV6_RECVDSTOPTS;
10478 				else
10479 					tcp->tcp_ipv6_recvancillary &=
10480 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10481 			}
10482 			break;
10483 		case IPV6_RECVRTHDR:
10484 			if (!checkonly) {
10485 				if (onoff)
10486 					tcp->tcp_ipv6_recvancillary |=
10487 					    TCP_IPV6_RECVRTHDR;
10488 				else
10489 					tcp->tcp_ipv6_recvancillary &=
10490 					    ~TCP_IPV6_RECVRTHDR;
10491 				PASS_OPT_TO_IP(connp);
10492 			}
10493 			break;
10494 		case IPV6_RECVRTHDRDSTOPTS:
10495 			if (!checkonly) {
10496 				if (onoff)
10497 					tcp->tcp_ipv6_recvancillary |=
10498 					    TCP_IPV6_RECVRTDSTOPTS;
10499 				else
10500 					tcp->tcp_ipv6_recvancillary &=
10501 					    ~TCP_IPV6_RECVRTDSTOPTS;
10502 				PASS_OPT_TO_IP(connp);
10503 			}
10504 			break;
10505 		case IPV6_PKTINFO:
10506 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10507 				return (EINVAL);
10508 			if (checkonly)
10509 				break;
10510 
10511 			if (inlen == 0) {
10512 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10513 			} else {
10514 				struct in6_pktinfo *pkti;
10515 
10516 				pkti = (struct in6_pktinfo *)invalp;
10517 				/*
10518 				 * RFC 3542 states that ipi6_addr must be
10519 				 * the unspecified address when setting the
10520 				 * IPV6_PKTINFO sticky socket option on a
10521 				 * TCP socket.
10522 				 */
10523 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10524 					return (EINVAL);
10525 				/*
10526 				 * IP will validate the source address and
10527 				 * interface index.
10528 				 */
10529 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10530 					reterr = ip_set_options(tcp->tcp_connp,
10531 					    level, name, invalp, inlen, cr);
10532 				} else {
10533 					reterr = ip6_set_pktinfo(cr,
10534 					    tcp->tcp_connp, pkti);
10535 				}
10536 				if (reterr != 0)
10537 					return (reterr);
10538 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10539 				ipp->ipp_addr = pkti->ipi6_addr;
10540 				if (ipp->ipp_ifindex != 0)
10541 					ipp->ipp_fields |= IPPF_IFINDEX;
10542 				else
10543 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10544 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10545 					ipp->ipp_fields |= IPPF_ADDR;
10546 				else
10547 					ipp->ipp_fields &= ~IPPF_ADDR;
10548 			}
10549 			reterr = tcp_build_hdrs(tcp);
10550 			if (reterr != 0)
10551 				return (reterr);
10552 			break;
10553 		case IPV6_TCLASS:
10554 			if (inlen != 0 && inlen != sizeof (int))
10555 				return (EINVAL);
10556 			if (checkonly)
10557 				break;
10558 
10559 			if (inlen == 0) {
10560 				ipp->ipp_fields &= ~IPPF_TCLASS;
10561 			} else {
10562 				if (*i1 > 255 || *i1 < -1)
10563 					return (EINVAL);
10564 				if (*i1 == -1) {
10565 					ipp->ipp_tclass = 0;
10566 					*i1 = 0;
10567 				} else {
10568 					ipp->ipp_tclass = *i1;
10569 				}
10570 				ipp->ipp_fields |= IPPF_TCLASS;
10571 			}
10572 			reterr = tcp_build_hdrs(tcp);
10573 			if (reterr != 0)
10574 				return (reterr);
10575 			break;
10576 		case IPV6_NEXTHOP:
10577 			/*
10578 			 * IP will verify that the nexthop is reachable
10579 			 * and fail for sticky options.
10580 			 */
10581 			if (inlen != 0 && inlen != sizeof (sin6_t))
10582 				return (EINVAL);
10583 			if (checkonly)
10584 				break;
10585 
10586 			if (inlen == 0) {
10587 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10588 			} else {
10589 				sin6_t *sin6 = (sin6_t *)invalp;
10590 
10591 				if (sin6->sin6_family != AF_INET6)
10592 					return (EAFNOSUPPORT);
10593 				if (IN6_IS_ADDR_V4MAPPED(
10594 				    &sin6->sin6_addr))
10595 					return (EADDRNOTAVAIL);
10596 				ipp->ipp_nexthop = sin6->sin6_addr;
10597 				if (!IN6_IS_ADDR_UNSPECIFIED(
10598 				    &ipp->ipp_nexthop))
10599 					ipp->ipp_fields |= IPPF_NEXTHOP;
10600 				else
10601 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10602 			}
10603 			reterr = tcp_build_hdrs(tcp);
10604 			if (reterr != 0)
10605 				return (reterr);
10606 			PASS_OPT_TO_IP(connp);
10607 			break;
10608 		case IPV6_HOPOPTS: {
10609 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10610 
10611 			/*
10612 			 * Sanity checks - minimum size, size a multiple of
10613 			 * eight bytes, and matching size passed in.
10614 			 */
10615 			if (inlen != 0 &&
10616 			    inlen != (8 * (hopts->ip6h_len + 1)))
10617 				return (EINVAL);
10618 
10619 			if (checkonly)
10620 				break;
10621 
10622 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10623 			    (uchar_t **)&ipp->ipp_hopopts,
10624 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10625 			if (reterr != 0)
10626 				return (reterr);
10627 			if (ipp->ipp_hopoptslen == 0)
10628 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10629 			else
10630 				ipp->ipp_fields |= IPPF_HOPOPTS;
10631 			reterr = tcp_build_hdrs(tcp);
10632 			if (reterr != 0)
10633 				return (reterr);
10634 			break;
10635 		}
10636 		case IPV6_RTHDRDSTOPTS: {
10637 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10638 
10639 			/*
10640 			 * Sanity checks - minimum size, size a multiple of
10641 			 * eight bytes, and matching size passed in.
10642 			 */
10643 			if (inlen != 0 &&
10644 			    inlen != (8 * (dopts->ip6d_len + 1)))
10645 				return (EINVAL);
10646 
10647 			if (checkonly)
10648 				break;
10649 
10650 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10651 			    (uchar_t **)&ipp->ipp_rtdstopts,
10652 			    &ipp->ipp_rtdstoptslen, 0);
10653 			if (reterr != 0)
10654 				return (reterr);
10655 			if (ipp->ipp_rtdstoptslen == 0)
10656 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10657 			else
10658 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10659 			reterr = tcp_build_hdrs(tcp);
10660 			if (reterr != 0)
10661 				return (reterr);
10662 			break;
10663 		}
10664 		case IPV6_DSTOPTS: {
10665 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10666 
10667 			/*
10668 			 * Sanity checks - minimum size, size a multiple of
10669 			 * eight bytes, and matching size passed in.
10670 			 */
10671 			if (inlen != 0 &&
10672 			    inlen != (8 * (dopts->ip6d_len + 1)))
10673 				return (EINVAL);
10674 
10675 			if (checkonly)
10676 				break;
10677 
10678 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10679 			    (uchar_t **)&ipp->ipp_dstopts,
10680 			    &ipp->ipp_dstoptslen, 0);
10681 			if (reterr != 0)
10682 				return (reterr);
10683 			if (ipp->ipp_dstoptslen == 0)
10684 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10685 			else
10686 				ipp->ipp_fields |= IPPF_DSTOPTS;
10687 			reterr = tcp_build_hdrs(tcp);
10688 			if (reterr != 0)
10689 				return (reterr);
10690 			break;
10691 		}
10692 		case IPV6_RTHDR: {
10693 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10694 
10695 			/*
10696 			 * Sanity checks - minimum size, size a multiple of
10697 			 * eight bytes, and matching size passed in.
10698 			 */
10699 			if (inlen != 0 &&
10700 			    inlen != (8 * (rt->ip6r_len + 1)))
10701 				return (EINVAL);
10702 
10703 			if (checkonly)
10704 				break;
10705 
10706 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10707 			    (uchar_t **)&ipp->ipp_rthdr,
10708 			    &ipp->ipp_rthdrlen, 0);
10709 			if (reterr != 0)
10710 				return (reterr);
10711 			if (ipp->ipp_rthdrlen == 0)
10712 				ipp->ipp_fields &= ~IPPF_RTHDR;
10713 			else
10714 				ipp->ipp_fields |= IPPF_RTHDR;
10715 			reterr = tcp_build_hdrs(tcp);
10716 			if (reterr != 0)
10717 				return (reterr);
10718 			break;
10719 		}
10720 		case IPV6_V6ONLY:
10721 			if (!checkonly) {
10722 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10723 			}
10724 			break;
10725 		case IPV6_USE_MIN_MTU:
10726 			if (inlen != sizeof (int))
10727 				return (EINVAL);
10728 
10729 			if (*i1 < -1 || *i1 > 1)
10730 				return (EINVAL);
10731 
10732 			if (checkonly)
10733 				break;
10734 
10735 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10736 			ipp->ipp_use_min_mtu = *i1;
10737 			break;
10738 		case IPV6_SEC_OPT:
10739 			/*
10740 			 * We should not allow policy setting after
10741 			 * we start listening for connections.
10742 			 */
10743 			if (tcp->tcp_state == TCPS_LISTEN) {
10744 				return (EINVAL);
10745 			} else {
10746 				/* Handled at the IP level */
10747 				return (-EINVAL);
10748 			}
10749 		case IPV6_SRC_PREFERENCES:
10750 			if (inlen != sizeof (uint32_t))
10751 				return (EINVAL);
10752 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10753 			    *(uint32_t *)invalp);
10754 			if (reterr != 0) {
10755 				*outlenp = 0;
10756 				return (reterr);
10757 			}
10758 			break;
10759 		default:
10760 			*outlenp = 0;
10761 			return (EINVAL);
10762 		}
10763 		break;
10764 	}		/* end IPPROTO_IPV6 */
10765 	default:
10766 		*outlenp = 0;
10767 		return (EINVAL);
10768 	}
10769 	/*
10770 	 * Common case of OK return with outval same as inval
10771 	 */
10772 	if (invalp != outvalp) {
10773 		/* don't trust bcopy for identical src/dst */
10774 		(void) bcopy(invalp, outvalp, inlen);
10775 	}
10776 	*outlenp = inlen;
10777 	return (0);
10778 }
10779 
10780 /* ARGSUSED */
10781 int
10782 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10783     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10784     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10785 {
10786 	conn_t	*connp =  Q_TO_CONN(q);
10787 
10788 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10789 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10790 }
10791 
10792 int
10793 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10794     const void *optvalp, socklen_t optlen, cred_t *cr)
10795 {
10796 	conn_t		*connp = (conn_t *)proto_handle;
10797 	squeue_t	*sqp = connp->conn_sqp;
10798 	int		error;
10799 
10800 	ASSERT(connp->conn_upper_handle != NULL);
10801 	/*
10802 	 * Entering the squeue synchronously can result in a context switch,
10803 	 * which can cause a rather sever performance degradation. So we try to
10804 	 * handle whatever options we can without entering the squeue.
10805 	 */
10806 	if (level == IPPROTO_TCP) {
10807 		switch (option_name) {
10808 		case TCP_NODELAY:
10809 			if (optlen != sizeof (int32_t))
10810 				return (EINVAL);
10811 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10812 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10813 			    connp->conn_tcp->tcp_mss;
10814 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10815 			return (0);
10816 		default:
10817 			break;
10818 		}
10819 	}
10820 
10821 	error = squeue_synch_enter(sqp, connp, NULL);
10822 	if (error == ENOMEM) {
10823 		return (ENOMEM);
10824 	}
10825 
10826 	error = proto_opt_check(level, option_name, optlen, NULL,
10827 	    tcp_opt_obj.odb_opt_des_arr,
10828 	    tcp_opt_obj.odb_opt_arr_cnt,
10829 	    tcp_opt_obj.odb_topmost_tpiprovider,
10830 	    B_TRUE, B_FALSE, cr);
10831 
10832 	if (error != 0) {
10833 		if (error < 0) {
10834 			error = proto_tlitosyserr(-error);
10835 		}
10836 		squeue_synch_exit(sqp, connp);
10837 		return (error);
10838 	}
10839 
10840 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10841 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10842 	    NULL, cr, NULL);
10843 	squeue_synch_exit(sqp, connp);
10844 
10845 	if (error < 0) {
10846 		/*
10847 		 * Pass on to ip
10848 		 */
10849 		error = ip_set_options(connp, level, option_name, optvalp,
10850 		    optlen, cr);
10851 	}
10852 	return (error);
10853 }
10854 
10855 /*
10856  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10857  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10858  * headers, and the maximum size tcp header (to avoid reallocation
10859  * on the fly for additional tcp options).
10860  * Returns failure if can't allocate memory.
10861  */
10862 static int
10863 tcp_build_hdrs(tcp_t *tcp)
10864 {
10865 	char	*hdrs;
10866 	uint_t	hdrs_len;
10867 	ip6i_t	*ip6i;
10868 	char	buf[TCP_MAX_HDR_LENGTH];
10869 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10870 	in6_addr_t src, dst;
10871 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10872 	conn_t *connp = tcp->tcp_connp;
10873 
10874 	/*
10875 	 * save the existing tcp header and source/dest IP addresses
10876 	 */
10877 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10878 	src = tcp->tcp_ip6h->ip6_src;
10879 	dst = tcp->tcp_ip6h->ip6_dst;
10880 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10881 	ASSERT(hdrs_len != 0);
10882 	if (hdrs_len > tcp->tcp_iphc_len) {
10883 		/* Need to reallocate */
10884 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10885 		if (hdrs == NULL)
10886 			return (ENOMEM);
10887 		if (tcp->tcp_iphc != NULL) {
10888 			if (tcp->tcp_hdr_grown) {
10889 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10890 			} else {
10891 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10892 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10893 			}
10894 			tcp->tcp_iphc_len = 0;
10895 		}
10896 		ASSERT(tcp->tcp_iphc_len == 0);
10897 		tcp->tcp_iphc = hdrs;
10898 		tcp->tcp_iphc_len = hdrs_len;
10899 		tcp->tcp_hdr_grown = B_TRUE;
10900 	}
10901 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10902 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10903 
10904 	/* Set header fields not in ipp */
10905 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10906 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10907 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10908 	} else {
10909 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10910 	}
10911 	/*
10912 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10913 	 *
10914 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10915 	 */
10916 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10917 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10918 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10919 
10920 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10921 
10922 	tcp->tcp_ip6h->ip6_src = src;
10923 	tcp->tcp_ip6h->ip6_dst = dst;
10924 
10925 	/*
10926 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10927 	 * the default value for TCP.
10928 	 */
10929 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10930 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10931 
10932 	/*
10933 	 * If we're setting extension headers after a connection
10934 	 * has been established, and if we have a routing header
10935 	 * among the extension headers, call ip_massage_options_v6 to
10936 	 * manipulate the routing header/ip6_dst set the checksum
10937 	 * difference in the tcp header template.
10938 	 * (This happens in tcp_connect_ipv6 if the routing header
10939 	 * is set prior to the connect.)
10940 	 * Set the tcp_sum to zero first in case we've cleared a
10941 	 * routing header or don't have one at all.
10942 	 */
10943 	tcp->tcp_sum = 0;
10944 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10945 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10946 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10947 		    (uint8_t *)tcp->tcp_tcph);
10948 		if (rth != NULL) {
10949 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10950 			    rth, tcps->tcps_netstack);
10951 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10952 			    (tcp->tcp_sum >> 16));
10953 		}
10954 	}
10955 
10956 	/* Try to get everything in a single mblk */
10957 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10958 	    hdrs_len + tcps->tcps_wroff_xtra);
10959 	return (0);
10960 }
10961 
10962 /*
10963  * Transfer any source route option from ipha to buf/dst in reversed form.
10964  */
10965 static int
10966 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10967 {
10968 	ipoptp_t	opts;
10969 	uchar_t		*opt;
10970 	uint8_t		optval;
10971 	uint8_t		optlen;
10972 	uint32_t	len = 0;
10973 
10974 	for (optval = ipoptp_first(&opts, ipha);
10975 	    optval != IPOPT_EOL;
10976 	    optval = ipoptp_next(&opts)) {
10977 		opt = opts.ipoptp_cur;
10978 		optlen = opts.ipoptp_len;
10979 		switch (optval) {
10980 			int	off1, off2;
10981 		case IPOPT_SSRR:
10982 		case IPOPT_LSRR:
10983 
10984 			/* Reverse source route */
10985 			/*
10986 			 * First entry should be the next to last one in the
10987 			 * current source route (the last entry is our
10988 			 * address.)
10989 			 * The last entry should be the final destination.
10990 			 */
10991 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10992 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10993 			off1 = IPOPT_MINOFF_SR - 1;
10994 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10995 			if (off2 < 0) {
10996 				/* No entries in source route */
10997 				break;
10998 			}
10999 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11000 			/*
11001 			 * Note: use src since ipha has not had its src
11002 			 * and dst reversed (it is in the state it was
11003 			 * received.
11004 			 */
11005 			bcopy(&ipha->ipha_src, buf + off2,
11006 			    IP_ADDR_LEN);
11007 			off2 -= IP_ADDR_LEN;
11008 
11009 			while (off2 > 0) {
11010 				bcopy(opt + off2, buf + off1,
11011 				    IP_ADDR_LEN);
11012 				off1 += IP_ADDR_LEN;
11013 				off2 -= IP_ADDR_LEN;
11014 			}
11015 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11016 			buf += optlen;
11017 			len += optlen;
11018 			break;
11019 		}
11020 	}
11021 done:
11022 	/* Pad the resulting options */
11023 	while (len & 0x3) {
11024 		*buf++ = IPOPT_EOL;
11025 		len++;
11026 	}
11027 	return (len);
11028 }
11029 
11030 
11031 /*
11032  * Extract and revert a source route from ipha (if any)
11033  * and then update the relevant fields in both tcp_t and the standard header.
11034  */
11035 static void
11036 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11037 {
11038 	char	buf[TCP_MAX_HDR_LENGTH];
11039 	uint_t	tcph_len;
11040 	int	len;
11041 
11042 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11043 	len = IPH_HDR_LENGTH(ipha);
11044 	if (len == IP_SIMPLE_HDR_LENGTH)
11045 		/* Nothing to do */
11046 		return;
11047 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11048 	    (len & 0x3))
11049 		return;
11050 
11051 	tcph_len = tcp->tcp_tcp_hdr_len;
11052 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11053 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11054 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11055 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11056 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11057 	len += IP_SIMPLE_HDR_LENGTH;
11058 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11059 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11060 	if ((int)tcp->tcp_sum < 0)
11061 		tcp->tcp_sum--;
11062 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11063 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11064 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11065 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11066 	tcp->tcp_ip_hdr_len = len;
11067 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11068 	    (IP_VERSION << 4) | (len >> 2);
11069 	len += tcph_len;
11070 	tcp->tcp_hdr_len = len;
11071 }
11072 
11073 /*
11074  * Copy the standard header into its new location,
11075  * lay in the new options and then update the relevant
11076  * fields in both tcp_t and the standard header.
11077  */
11078 static int
11079 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11080 {
11081 	uint_t	tcph_len;
11082 	uint8_t	*ip_optp;
11083 	tcph_t	*new_tcph;
11084 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11085 	conn_t	*connp = tcp->tcp_connp;
11086 
11087 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11088 		return (EINVAL);
11089 
11090 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11091 		return (EINVAL);
11092 
11093 	if (checkonly) {
11094 		/*
11095 		 * do not really set, just pretend to - T_CHECK
11096 		 */
11097 		return (0);
11098 	}
11099 
11100 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11101 	if (tcp->tcp_label_len > 0) {
11102 		int padlen;
11103 		uint8_t opt;
11104 
11105 		/* convert list termination to no-ops */
11106 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11107 		ip_optp += ip_optp[IPOPT_OLEN];
11108 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11109 		while (--padlen >= 0)
11110 			*ip_optp++ = opt;
11111 	}
11112 	tcph_len = tcp->tcp_tcp_hdr_len;
11113 	new_tcph = (tcph_t *)(ip_optp + len);
11114 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11115 	tcp->tcp_tcph = new_tcph;
11116 	bcopy(ptr, ip_optp, len);
11117 
11118 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11119 
11120 	tcp->tcp_ip_hdr_len = len;
11121 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11122 	    (IP_VERSION << 4) | (len >> 2);
11123 	tcp->tcp_hdr_len = len + tcph_len;
11124 	if (!TCP_IS_DETACHED(tcp)) {
11125 		/* Always allocate room for all options. */
11126 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11127 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11128 	}
11129 	return (0);
11130 }
11131 
11132 /* Get callback routine passed to nd_load by tcp_param_register */
11133 /* ARGSUSED */
11134 static int
11135 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11136 {
11137 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11138 
11139 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11140 	return (0);
11141 }
11142 
11143 /*
11144  * Walk through the param array specified registering each element with the
11145  * named dispatch handler.
11146  */
11147 static boolean_t
11148 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11149 {
11150 	for (; cnt-- > 0; tcppa++) {
11151 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11152 			if (!nd_load(ndp, tcppa->tcp_param_name,
11153 			    tcp_param_get, tcp_param_set,
11154 			    (caddr_t)tcppa)) {
11155 				nd_free(ndp);
11156 				return (B_FALSE);
11157 			}
11158 		}
11159 	}
11160 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11161 	    KM_SLEEP);
11162 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11163 	    sizeof (tcpparam_t));
11164 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11165 	    tcp_param_get, tcp_param_set_aligned,
11166 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11167 		nd_free(ndp);
11168 		return (B_FALSE);
11169 	}
11170 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11171 	    KM_SLEEP);
11172 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11173 	    sizeof (tcpparam_t));
11174 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11175 	    tcp_param_get, tcp_param_set_aligned,
11176 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11177 		nd_free(ndp);
11178 		return (B_FALSE);
11179 	}
11180 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11181 	    KM_SLEEP);
11182 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11183 	    sizeof (tcpparam_t));
11184 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11185 	    tcp_param_get, tcp_param_set_aligned,
11186 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11187 		nd_free(ndp);
11188 		return (B_FALSE);
11189 	}
11190 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11191 	    KM_SLEEP);
11192 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11193 	    sizeof (tcpparam_t));
11194 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11195 	    tcp_param_get, tcp_param_set_aligned,
11196 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11197 		nd_free(ndp);
11198 		return (B_FALSE);
11199 	}
11200 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11201 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11202 		nd_free(ndp);
11203 		return (B_FALSE);
11204 	}
11205 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11206 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11207 		nd_free(ndp);
11208 		return (B_FALSE);
11209 	}
11210 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11211 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11212 		nd_free(ndp);
11213 		return (B_FALSE);
11214 	}
11215 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11216 	    tcp_1948_phrase_set, NULL)) {
11217 		nd_free(ndp);
11218 		return (B_FALSE);
11219 	}
11220 	/*
11221 	 * Dummy ndd variables - only to convey obsolescence information
11222 	 * through printing of their name (no get or set routines)
11223 	 * XXX Remove in future releases ?
11224 	 */
11225 	if (!nd_load(ndp,
11226 	    "tcp_close_wait_interval(obsoleted - "
11227 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11228 		nd_free(ndp);
11229 		return (B_FALSE);
11230 	}
11231 	return (B_TRUE);
11232 }
11233 
11234 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11235 /* ARGSUSED */
11236 static int
11237 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11238     cred_t *cr)
11239 {
11240 	long new_value;
11241 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11242 
11243 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11244 	    new_value < tcppa->tcp_param_min ||
11245 	    new_value > tcppa->tcp_param_max) {
11246 		return (EINVAL);
11247 	}
11248 	/*
11249 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11250 	 * round it up.  For future 64 bit requirement, we actually make it
11251 	 * a multiple of 8.
11252 	 */
11253 	if (new_value & 0x7) {
11254 		new_value = (new_value & ~0x7) + 0x8;
11255 	}
11256 	tcppa->tcp_param_val = new_value;
11257 	return (0);
11258 }
11259 
11260 /* Set callback routine passed to nd_load by tcp_param_register */
11261 /* ARGSUSED */
11262 static int
11263 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11264 {
11265 	long	new_value;
11266 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11267 
11268 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11269 	    new_value < tcppa->tcp_param_min ||
11270 	    new_value > tcppa->tcp_param_max) {
11271 		return (EINVAL);
11272 	}
11273 	tcppa->tcp_param_val = new_value;
11274 	return (0);
11275 }
11276 
11277 /*
11278  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11279  * is filled, return as much as we can.  The message passed in may be
11280  * multi-part, chained using b_cont.  "start" is the starting sequence
11281  * number for this piece.
11282  */
11283 static mblk_t *
11284 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11285 {
11286 	uint32_t	end;
11287 	mblk_t		*mp1;
11288 	mblk_t		*mp2;
11289 	mblk_t		*next_mp;
11290 	uint32_t	u1;
11291 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11292 
11293 	/* Walk through all the new pieces. */
11294 	do {
11295 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11296 		    (uintptr_t)INT_MAX);
11297 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11298 		next_mp = mp->b_cont;
11299 		if (start == end) {
11300 			/* Empty.  Blast it. */
11301 			freeb(mp);
11302 			continue;
11303 		}
11304 		mp->b_cont = NULL;
11305 		TCP_REASS_SET_SEQ(mp, start);
11306 		TCP_REASS_SET_END(mp, end);
11307 		mp1 = tcp->tcp_reass_tail;
11308 		if (!mp1) {
11309 			tcp->tcp_reass_tail = mp;
11310 			tcp->tcp_reass_head = mp;
11311 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11312 			UPDATE_MIB(&tcps->tcps_mib,
11313 			    tcpInDataUnorderBytes, end - start);
11314 			continue;
11315 		}
11316 		/* New stuff completely beyond tail? */
11317 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11318 			/* Link it on end. */
11319 			mp1->b_cont = mp;
11320 			tcp->tcp_reass_tail = mp;
11321 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11322 			UPDATE_MIB(&tcps->tcps_mib,
11323 			    tcpInDataUnorderBytes, end - start);
11324 			continue;
11325 		}
11326 		mp1 = tcp->tcp_reass_head;
11327 		u1 = TCP_REASS_SEQ(mp1);
11328 		/* New stuff at the front? */
11329 		if (SEQ_LT(start, u1)) {
11330 			/* Yes... Check for overlap. */
11331 			mp->b_cont = mp1;
11332 			tcp->tcp_reass_head = mp;
11333 			tcp_reass_elim_overlap(tcp, mp);
11334 			continue;
11335 		}
11336 		/*
11337 		 * The new piece fits somewhere between the head and tail.
11338 		 * We find our slot, where mp1 precedes us and mp2 trails.
11339 		 */
11340 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11341 			u1 = TCP_REASS_SEQ(mp2);
11342 			if (SEQ_LEQ(start, u1))
11343 				break;
11344 		}
11345 		/* Link ourselves in */
11346 		mp->b_cont = mp2;
11347 		mp1->b_cont = mp;
11348 
11349 		/* Trim overlap with following mblk(s) first */
11350 		tcp_reass_elim_overlap(tcp, mp);
11351 
11352 		/* Trim overlap with preceding mblk */
11353 		tcp_reass_elim_overlap(tcp, mp1);
11354 
11355 	} while (start = end, mp = next_mp);
11356 	mp1 = tcp->tcp_reass_head;
11357 	/* Anything ready to go? */
11358 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11359 		return (NULL);
11360 	/* Eat what we can off the queue */
11361 	for (;;) {
11362 		mp = mp1->b_cont;
11363 		end = TCP_REASS_END(mp1);
11364 		TCP_REASS_SET_SEQ(mp1, 0);
11365 		TCP_REASS_SET_END(mp1, 0);
11366 		if (!mp) {
11367 			tcp->tcp_reass_tail = NULL;
11368 			break;
11369 		}
11370 		if (end != TCP_REASS_SEQ(mp)) {
11371 			mp1->b_cont = NULL;
11372 			break;
11373 		}
11374 		mp1 = mp;
11375 	}
11376 	mp1 = tcp->tcp_reass_head;
11377 	tcp->tcp_reass_head = mp;
11378 	return (mp1);
11379 }
11380 
11381 /* Eliminate any overlap that mp may have over later mblks */
11382 static void
11383 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11384 {
11385 	uint32_t	end;
11386 	mblk_t		*mp1;
11387 	uint32_t	u1;
11388 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11389 
11390 	end = TCP_REASS_END(mp);
11391 	while ((mp1 = mp->b_cont) != NULL) {
11392 		u1 = TCP_REASS_SEQ(mp1);
11393 		if (!SEQ_GT(end, u1))
11394 			break;
11395 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11396 			mp->b_wptr -= end - u1;
11397 			TCP_REASS_SET_END(mp, u1);
11398 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11399 			UPDATE_MIB(&tcps->tcps_mib,
11400 			    tcpInDataPartDupBytes, end - u1);
11401 			break;
11402 		}
11403 		mp->b_cont = mp1->b_cont;
11404 		TCP_REASS_SET_SEQ(mp1, 0);
11405 		TCP_REASS_SET_END(mp1, 0);
11406 		freeb(mp1);
11407 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11408 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11409 	}
11410 	if (!mp1)
11411 		tcp->tcp_reass_tail = mp;
11412 }
11413 
11414 static uint_t
11415 tcp_rwnd_reopen(tcp_t *tcp)
11416 {
11417 	uint_t ret = 0;
11418 	uint_t thwin;
11419 
11420 	/* Learn the latest rwnd information that we sent to the other side. */
11421 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11422 	    << tcp->tcp_rcv_ws;
11423 	/* This is peer's calculated send window (our receive window). */
11424 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11425 	/*
11426 	 * Increase the receive window to max.  But we need to do receiver
11427 	 * SWS avoidance.  This means that we need to check the increase of
11428 	 * of receive window is at least 1 MSS.
11429 	 */
11430 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11431 		/*
11432 		 * If the window that the other side knows is less than max
11433 		 * deferred acks segments, send an update immediately.
11434 		 */
11435 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11436 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11437 			ret = TH_ACK_NEEDED;
11438 		}
11439 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11440 	}
11441 	return (ret);
11442 }
11443 
11444 /*
11445  * Send up all messages queued on tcp_rcv_list.
11446  */
11447 static uint_t
11448 tcp_rcv_drain(tcp_t *tcp)
11449 {
11450 	mblk_t *mp;
11451 	uint_t ret = 0;
11452 #ifdef DEBUG
11453 	uint_t cnt = 0;
11454 #endif
11455 	queue_t	*q = tcp->tcp_rq;
11456 
11457 	/* Can't drain on an eager connection */
11458 	if (tcp->tcp_listener != NULL)
11459 		return (ret);
11460 
11461 	/* Can't be a non-STREAMS connection */
11462 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
11463 
11464 	/* No need for the push timer now. */
11465 	if (tcp->tcp_push_tid != 0) {
11466 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11467 		tcp->tcp_push_tid = 0;
11468 	}
11469 
11470 	/*
11471 	 * Handle two cases here: we are currently fused or we were
11472 	 * previously fused and have some urgent data to be delivered
11473 	 * upstream.  The latter happens because we either ran out of
11474 	 * memory or were detached and therefore sending the SIGURG was
11475 	 * deferred until this point.  In either case we pass control
11476 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11477 	 * some work.
11478 	 */
11479 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11480 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11481 		    tcp->tcp_fused_sigurg_mp != NULL);
11482 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11483 		    &tcp->tcp_fused_sigurg_mp))
11484 			return (ret);
11485 	}
11486 
11487 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11488 		tcp->tcp_rcv_list = mp->b_next;
11489 		mp->b_next = NULL;
11490 #ifdef DEBUG
11491 		cnt += msgdsize(mp);
11492 #endif
11493 		/* Does this need SSL processing first? */
11494 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11495 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11496 			    mblk_t *, mp);
11497 			tcp_kssl_input(tcp, mp);
11498 			continue;
11499 		}
11500 		putnext(q, mp);
11501 	}
11502 #ifdef DEBUG
11503 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11504 #endif
11505 	tcp->tcp_rcv_last_head = NULL;
11506 	tcp->tcp_rcv_last_tail = NULL;
11507 	tcp->tcp_rcv_cnt = 0;
11508 
11509 	if (canputnext(q))
11510 		return (tcp_rwnd_reopen(tcp));
11511 
11512 	return (ret);
11513 }
11514 
11515 /*
11516  * Queue data on tcp_rcv_list which is a b_next chain.
11517  * tcp_rcv_last_head/tail is the last element of this chain.
11518  * Each element of the chain is a b_cont chain.
11519  *
11520  * M_DATA messages are added to the current element.
11521  * Other messages are added as new (b_next) elements.
11522  */
11523 void
11524 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11525 {
11526 	ASSERT(seg_len == msgdsize(mp));
11527 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11528 
11529 	if (tcp->tcp_rcv_list == NULL) {
11530 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11531 		tcp->tcp_rcv_list = mp;
11532 		tcp->tcp_rcv_last_head = mp;
11533 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11534 		tcp->tcp_rcv_last_tail->b_cont = mp;
11535 	} else {
11536 		tcp->tcp_rcv_last_head->b_next = mp;
11537 		tcp->tcp_rcv_last_head = mp;
11538 	}
11539 
11540 	while (mp->b_cont)
11541 		mp = mp->b_cont;
11542 
11543 	tcp->tcp_rcv_last_tail = mp;
11544 	tcp->tcp_rcv_cnt += seg_len;
11545 	tcp->tcp_rwnd -= seg_len;
11546 }
11547 
11548 /*
11549  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11550  *
11551  * This is the default entry function into TCP on the read side. TCP is
11552  * always entered via squeue i.e. using squeue's for mutual exclusion.
11553  * When classifier does a lookup to find the tcp, it also puts a reference
11554  * on the conn structure associated so the tcp is guaranteed to exist
11555  * when we come here. We still need to check the state because it might
11556  * as well has been closed. The squeue processing function i.e. squeue_enter,
11557  * is responsible for doing the CONN_DEC_REF.
11558  *
11559  * Apart from the default entry point, IP also sends packets directly to
11560  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11561  * connections.
11562  */
11563 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11564 void
11565 tcp_input(void *arg, mblk_t *mp, void *arg2)
11566 {
11567 	conn_t	*connp = (conn_t *)arg;
11568 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11569 
11570 	/* arg2 is the sqp */
11571 	ASSERT(arg2 != NULL);
11572 	ASSERT(mp != NULL);
11573 
11574 	/*
11575 	 * Don't accept any input on a closed tcp as this TCP logically does
11576 	 * not exist on the system. Don't proceed further with this TCP.
11577 	 * For eg. this packet could trigger another close of this tcp
11578 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11579 	 * tcp_clean_death / tcp_closei_local must be called at most once
11580 	 * on a TCP. In this case we need to refeed the packet into the
11581 	 * classifier and figure out where the packet should go. Need to
11582 	 * preserve the recv_ill somehow. Until we figure that out, for
11583 	 * now just drop the packet if we can't classify the packet.
11584 	 */
11585 	if (tcp->tcp_state == TCPS_CLOSED ||
11586 	    tcp->tcp_state == TCPS_BOUND) {
11587 		conn_t	*new_connp;
11588 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11589 
11590 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11591 		if (new_connp != NULL) {
11592 			tcp_reinput(new_connp, mp, arg2);
11593 			return;
11594 		}
11595 		/* We failed to classify. For now just drop the packet */
11596 		freemsg(mp);
11597 		return;
11598 	}
11599 
11600 	if (DB_TYPE(mp) != M_DATA) {
11601 		tcp_rput_common(tcp, mp);
11602 		return;
11603 	}
11604 
11605 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11606 		squeue_t	*final_sqp;
11607 
11608 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11609 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11610 		DB_CKSUMSTART(mp) = 0;
11611 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11612 		    connp->conn_final_sqp == NULL &&
11613 		    tcp_outbound_squeue_switch) {
11614 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11615 			connp->conn_final_sqp = final_sqp;
11616 			if (connp->conn_final_sqp != connp->conn_sqp) {
11617 				CONN_INC_REF(connp);
11618 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11619 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11620 				    tcp_rput_data, connp, ip_squeue_flag,
11621 				    SQTAG_CONNECT_FINISH);
11622 				return;
11623 			}
11624 		}
11625 	}
11626 	tcp_rput_data(connp, mp, arg2);
11627 }
11628 
11629 /*
11630  * The read side put procedure.
11631  * The packets passed up by ip are assume to be aligned according to
11632  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11633  */
11634 static void
11635 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11636 {
11637 	/*
11638 	 * tcp_rput_data() does not expect M_CTL except for the case
11639 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11640 	 * type. Need to make sure that any other M_CTLs don't make
11641 	 * it to tcp_rput_data since it is not expecting any and doesn't
11642 	 * check for it.
11643 	 */
11644 	if (DB_TYPE(mp) == M_CTL) {
11645 		switch (*(uint32_t *)(mp->b_rptr)) {
11646 		case TCP_IOC_ABORT_CONN:
11647 			/*
11648 			 * Handle connection abort request.
11649 			 */
11650 			tcp_ioctl_abort_handler(tcp, mp);
11651 			return;
11652 		case IPSEC_IN:
11653 			/*
11654 			 * Only secure icmp arrive in TCP and they
11655 			 * don't go through data path.
11656 			 */
11657 			tcp_icmp_error(tcp, mp);
11658 			return;
11659 		case IN_PKTINFO:
11660 			/*
11661 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11662 			 * sockets that are receiving IPv4 traffic. tcp
11663 			 */
11664 			ASSERT(tcp->tcp_family == AF_INET6);
11665 			ASSERT(tcp->tcp_ipv6_recvancillary &
11666 			    TCP_IPV6_RECVPKTINFO);
11667 			tcp_rput_data(tcp->tcp_connp, mp,
11668 			    tcp->tcp_connp->conn_sqp);
11669 			return;
11670 		case MDT_IOC_INFO_UPDATE:
11671 			/*
11672 			 * Handle Multidata information update; the
11673 			 * following routine will free the message.
11674 			 */
11675 			if (tcp->tcp_connp->conn_mdt_ok) {
11676 				tcp_mdt_update(tcp,
11677 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11678 				    B_FALSE);
11679 			}
11680 			freemsg(mp);
11681 			return;
11682 		case LSO_IOC_INFO_UPDATE:
11683 			/*
11684 			 * Handle LSO information update; the following
11685 			 * routine will free the message.
11686 			 */
11687 			if (tcp->tcp_connp->conn_lso_ok) {
11688 				tcp_lso_update(tcp,
11689 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11690 			}
11691 			freemsg(mp);
11692 			return;
11693 		default:
11694 			/*
11695 			 * tcp_icmp_err() will process the M_CTL packets.
11696 			 * Non-ICMP packets, if any, will be discarded in
11697 			 * tcp_icmp_err(). We will process the ICMP packet
11698 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11699 			 * incoming ICMP packet may result in changing
11700 			 * the tcp_mss, which we would need if we have
11701 			 * packets to retransmit.
11702 			 */
11703 			tcp_icmp_error(tcp, mp);
11704 			return;
11705 		}
11706 	}
11707 
11708 	/* No point processing the message if tcp is already closed */
11709 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11710 		freemsg(mp);
11711 		return;
11712 	}
11713 
11714 	tcp_rput_other(tcp, mp);
11715 }
11716 
11717 
11718 /* The minimum of smoothed mean deviation in RTO calculation. */
11719 #define	TCP_SD_MIN	400
11720 
11721 /*
11722  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11723  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11724  * are the same as those in Appendix A.2 of that paper.
11725  *
11726  * m = new measurement
11727  * sa = smoothed RTT average (8 * average estimates).
11728  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11729  */
11730 static void
11731 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11732 {
11733 	long m = TICK_TO_MSEC(rtt);
11734 	clock_t sa = tcp->tcp_rtt_sa;
11735 	clock_t sv = tcp->tcp_rtt_sd;
11736 	clock_t rto;
11737 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11738 
11739 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11740 	tcp->tcp_rtt_update++;
11741 
11742 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11743 	if (sa != 0) {
11744 		/*
11745 		 * Update average estimator:
11746 		 *	new rtt = 7/8 old rtt + 1/8 Error
11747 		 */
11748 
11749 		/* m is now Error in estimate. */
11750 		m -= sa >> 3;
11751 		if ((sa += m) <= 0) {
11752 			/*
11753 			 * Don't allow the smoothed average to be negative.
11754 			 * We use 0 to denote reinitialization of the
11755 			 * variables.
11756 			 */
11757 			sa = 1;
11758 		}
11759 
11760 		/*
11761 		 * Update deviation estimator:
11762 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11763 		 */
11764 		if (m < 0)
11765 			m = -m;
11766 		m -= sv >> 2;
11767 		sv += m;
11768 	} else {
11769 		/*
11770 		 * This follows BSD's implementation.  So the reinitialized
11771 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11772 		 * link is bandwidth dominated, doubling the window size
11773 		 * during slow start means doubling the RTT.  We want to be
11774 		 * more conservative when we reinitialize our estimates.  3
11775 		 * is just a convenient number.
11776 		 */
11777 		sa = m << 3;
11778 		sv = m << 1;
11779 	}
11780 	if (sv < TCP_SD_MIN) {
11781 		/*
11782 		 * We do not know that if sa captures the delay ACK
11783 		 * effect as in a long train of segments, a receiver
11784 		 * does not delay its ACKs.  So set the minimum of sv
11785 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11786 		 * of BSD DATO.  That means the minimum of mean
11787 		 * deviation is 100 ms.
11788 		 *
11789 		 */
11790 		sv = TCP_SD_MIN;
11791 	}
11792 	tcp->tcp_rtt_sa = sa;
11793 	tcp->tcp_rtt_sd = sv;
11794 	/*
11795 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11796 	 *
11797 	 * Add tcp_rexmit_interval extra in case of extreme environment
11798 	 * where the algorithm fails to work.  The default value of
11799 	 * tcp_rexmit_interval_extra should be 0.
11800 	 *
11801 	 * As we use a finer grained clock than BSD and update
11802 	 * RTO for every ACKs, add in another .25 of RTT to the
11803 	 * deviation of RTO to accomodate burstiness of 1/4 of
11804 	 * window size.
11805 	 */
11806 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11807 
11808 	if (rto > tcps->tcps_rexmit_interval_max) {
11809 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11810 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11811 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11812 	} else {
11813 		tcp->tcp_rto = rto;
11814 	}
11815 
11816 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11817 	tcp->tcp_timer_backoff = 0;
11818 }
11819 
11820 /*
11821  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11822  * send queue which starts at the given sequence number. If the given
11823  * sequence number is equal to last valid sequence number (tcp_snxt), the
11824  * returned mblk is the last valid mblk, and off is set to the length of
11825  * that mblk.
11826  *
11827  * send queue which starts at the given seq. no.
11828  *
11829  * Parameters:
11830  *	tcp_t *tcp: the tcp instance pointer.
11831  *	uint32_t seq: the starting seq. no of the requested segment.
11832  *	int32_t *off: after the execution, *off will be the offset to
11833  *		the returned mblk which points to the requested seq no.
11834  *		It is the caller's responsibility to send in a non-null off.
11835  *
11836  * Return:
11837  *	A mblk_t pointer pointing to the requested segment in send queue.
11838  */
11839 static mblk_t *
11840 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11841 {
11842 	int32_t	cnt;
11843 	mblk_t	*mp;
11844 
11845 	/* Defensive coding.  Make sure we don't send incorrect data. */
11846 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
11847 		return (NULL);
11848 
11849 	cnt = seq - tcp->tcp_suna;
11850 	mp = tcp->tcp_xmit_head;
11851 	while (cnt > 0 && mp != NULL) {
11852 		cnt -= mp->b_wptr - mp->b_rptr;
11853 		if (cnt <= 0) {
11854 			cnt += mp->b_wptr - mp->b_rptr;
11855 			break;
11856 		}
11857 		mp = mp->b_cont;
11858 	}
11859 	ASSERT(mp != NULL);
11860 	*off = cnt;
11861 	return (mp);
11862 }
11863 
11864 /*
11865  * This function handles all retransmissions if SACK is enabled for this
11866  * connection.  First it calculates how many segments can be retransmitted
11867  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11868  * segments.  A segment is eligible if sack_cnt for that segment is greater
11869  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11870  * all eligible segments, it checks to see if TCP can send some new segments
11871  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11872  *
11873  * Parameters:
11874  *	tcp_t *tcp: the tcp structure of the connection.
11875  *	uint_t *flags: in return, appropriate value will be set for
11876  *	tcp_rput_data().
11877  */
11878 static void
11879 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11880 {
11881 	notsack_blk_t	*notsack_blk;
11882 	int32_t		usable_swnd;
11883 	int32_t		mss;
11884 	uint32_t	seg_len;
11885 	mblk_t		*xmit_mp;
11886 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11887 
11888 	ASSERT(tcp->tcp_sack_info != NULL);
11889 	ASSERT(tcp->tcp_notsack_list != NULL);
11890 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11891 
11892 	/* Defensive coding in case there is a bug... */
11893 	if (tcp->tcp_notsack_list == NULL) {
11894 		return;
11895 	}
11896 	notsack_blk = tcp->tcp_notsack_list;
11897 	mss = tcp->tcp_mss;
11898 
11899 	/*
11900 	 * Limit the num of outstanding data in the network to be
11901 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11902 	 */
11903 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11904 
11905 	/* At least retransmit 1 MSS of data. */
11906 	if (usable_swnd <= 0) {
11907 		usable_swnd = mss;
11908 	}
11909 
11910 	/* Make sure no new RTT samples will be taken. */
11911 	tcp->tcp_csuna = tcp->tcp_snxt;
11912 
11913 	notsack_blk = tcp->tcp_notsack_list;
11914 	while (usable_swnd > 0) {
11915 		mblk_t		*snxt_mp, *tmp_mp;
11916 		tcp_seq		begin = tcp->tcp_sack_snxt;
11917 		tcp_seq		end;
11918 		int32_t		off;
11919 
11920 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11921 			if (SEQ_GT(notsack_blk->end, begin) &&
11922 			    (notsack_blk->sack_cnt >=
11923 			    tcps->tcps_dupack_fast_retransmit)) {
11924 				end = notsack_blk->end;
11925 				if (SEQ_LT(begin, notsack_blk->begin)) {
11926 					begin = notsack_blk->begin;
11927 				}
11928 				break;
11929 			}
11930 		}
11931 		/*
11932 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11933 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11934 		 * set to tcp_cwnd_ssthresh.
11935 		 */
11936 		if (notsack_blk == NULL) {
11937 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11938 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11939 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11940 				ASSERT(tcp->tcp_cwnd > 0);
11941 				return;
11942 			} else {
11943 				usable_swnd = usable_swnd / mss;
11944 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11945 				    MAX(usable_swnd * mss, mss);
11946 				*flags |= TH_XMIT_NEEDED;
11947 				return;
11948 			}
11949 		}
11950 
11951 		/*
11952 		 * Note that we may send more than usable_swnd allows here
11953 		 * because of round off, but no more than 1 MSS of data.
11954 		 */
11955 		seg_len = end - begin;
11956 		if (seg_len > mss)
11957 			seg_len = mss;
11958 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11959 		ASSERT(snxt_mp != NULL);
11960 		/* This should not happen.  Defensive coding again... */
11961 		if (snxt_mp == NULL) {
11962 			return;
11963 		}
11964 
11965 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11966 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11967 		if (xmit_mp == NULL)
11968 			return;
11969 
11970 		usable_swnd -= seg_len;
11971 		tcp->tcp_pipe += seg_len;
11972 		tcp->tcp_sack_snxt = begin + seg_len;
11973 
11974 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11975 
11976 		/*
11977 		 * Update the send timestamp to avoid false retransmission.
11978 		 */
11979 		snxt_mp->b_prev = (mblk_t *)lbolt;
11980 
11981 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
11982 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
11983 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
11984 		/*
11985 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11986 		 * This happens when new data sent during fast recovery is
11987 		 * also lost.  If TCP retransmits those new data, it needs
11988 		 * to extend SACK recover phase to avoid starting another
11989 		 * fast retransmit/recovery unnecessarily.
11990 		 */
11991 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11992 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11993 		}
11994 	}
11995 }
11996 
11997 /*
11998  * This function handles policy checking at TCP level for non-hard_bound/
11999  * detached connections.
12000  */
12001 static boolean_t
12002 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12003     boolean_t secure, boolean_t mctl_present)
12004 {
12005 	ipsec_latch_t *ipl = NULL;
12006 	ipsec_action_t *act = NULL;
12007 	mblk_t *data_mp;
12008 	ipsec_in_t *ii;
12009 	const char *reason;
12010 	kstat_named_t *counter;
12011 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12012 	ipsec_stack_t	*ipss;
12013 	ip_stack_t	*ipst;
12014 
12015 	ASSERT(mctl_present || !secure);
12016 
12017 	ASSERT((ipha == NULL && ip6h != NULL) ||
12018 	    (ip6h == NULL && ipha != NULL));
12019 
12020 	/*
12021 	 * We don't necessarily have an ipsec_in_act action to verify
12022 	 * policy because of assymetrical policy where we have only
12023 	 * outbound policy and no inbound policy (possible with global
12024 	 * policy).
12025 	 */
12026 	if (!secure) {
12027 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12028 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12029 			return (B_TRUE);
12030 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12031 		    "tcp_check_policy", ipha, ip6h, secure,
12032 		    tcps->tcps_netstack);
12033 		ipss = tcps->tcps_netstack->netstack_ipsec;
12034 
12035 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12036 		    DROPPER(ipss, ipds_tcp_clear),
12037 		    &tcps->tcps_dropper);
12038 		return (B_FALSE);
12039 	}
12040 
12041 	/*
12042 	 * We have a secure packet.
12043 	 */
12044 	if (act == NULL) {
12045 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12046 		    "tcp_check_policy", ipha, ip6h, secure,
12047 		    tcps->tcps_netstack);
12048 		ipss = tcps->tcps_netstack->netstack_ipsec;
12049 
12050 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12051 		    DROPPER(ipss, ipds_tcp_secure),
12052 		    &tcps->tcps_dropper);
12053 		return (B_FALSE);
12054 	}
12055 
12056 	/*
12057 	 * XXX This whole routine is currently incorrect.  ipl should
12058 	 * be set to the latch pointer, but is currently not set, so
12059 	 * we initialize it to NULL to avoid picking up random garbage.
12060 	 */
12061 	if (ipl == NULL)
12062 		return (B_TRUE);
12063 
12064 	data_mp = first_mp->b_cont;
12065 
12066 	ii = (ipsec_in_t *)first_mp->b_rptr;
12067 
12068 	ipst = tcps->tcps_netstack->netstack_ip;
12069 
12070 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12071 	    &counter, tcp->tcp_connp)) {
12072 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12073 		return (B_TRUE);
12074 	}
12075 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12076 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12077 	    reason);
12078 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12079 
12080 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12081 	    &tcps->tcps_dropper);
12082 	return (B_FALSE);
12083 }
12084 
12085 /*
12086  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12087  * retransmission after a timeout.
12088  *
12089  * To limit the number of duplicate segments, we limit the number of segment
12090  * to be sent in one time to tcp_snd_burst, the burst variable.
12091  */
12092 static void
12093 tcp_ss_rexmit(tcp_t *tcp)
12094 {
12095 	uint32_t	snxt;
12096 	uint32_t	smax;
12097 	int32_t		win;
12098 	int32_t		mss;
12099 	int32_t		off;
12100 	int32_t		burst = tcp->tcp_snd_burst;
12101 	mblk_t		*snxt_mp;
12102 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12103 
12104 	/*
12105 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12106 	 * all unack'ed segments.
12107 	 */
12108 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12109 		smax = tcp->tcp_rexmit_max;
12110 		snxt = tcp->tcp_rexmit_nxt;
12111 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12112 			snxt = tcp->tcp_suna;
12113 		}
12114 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12115 		win -= snxt - tcp->tcp_suna;
12116 		mss = tcp->tcp_mss;
12117 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12118 
12119 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12120 		    (burst > 0) && (snxt_mp != NULL)) {
12121 			mblk_t	*xmit_mp;
12122 			mblk_t	*old_snxt_mp = snxt_mp;
12123 			uint32_t cnt = mss;
12124 
12125 			if (win < cnt) {
12126 				cnt = win;
12127 			}
12128 			if (SEQ_GT(snxt + cnt, smax)) {
12129 				cnt = smax - snxt;
12130 			}
12131 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12132 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12133 			if (xmit_mp == NULL)
12134 				return;
12135 
12136 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12137 
12138 			snxt += cnt;
12139 			win -= cnt;
12140 			/*
12141 			 * Update the send timestamp to avoid false
12142 			 * retransmission.
12143 			 */
12144 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12145 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12146 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12147 
12148 			tcp->tcp_rexmit_nxt = snxt;
12149 			burst--;
12150 		}
12151 		/*
12152 		 * If we have transmitted all we have at the time
12153 		 * we started the retranmission, we can leave
12154 		 * the rest of the job to tcp_wput_data().  But we
12155 		 * need to check the send window first.  If the
12156 		 * win is not 0, go on with tcp_wput_data().
12157 		 */
12158 		if (SEQ_LT(snxt, smax) || win == 0) {
12159 			return;
12160 		}
12161 	}
12162 	/* Only call tcp_wput_data() if there is data to be sent. */
12163 	if (tcp->tcp_unsent) {
12164 		tcp_wput_data(tcp, NULL, B_FALSE);
12165 	}
12166 }
12167 
12168 /*
12169  * Process all TCP option in SYN segment.  Note that this function should
12170  * be called after tcp_adapt_ire() is called so that the necessary info
12171  * from IRE is already set in the tcp structure.
12172  *
12173  * This function sets up the correct tcp_mss value according to the
12174  * MSS option value and our header size.  It also sets up the window scale
12175  * and timestamp values, and initialize SACK info blocks.  But it does not
12176  * change receive window size after setting the tcp_mss value.  The caller
12177  * should do the appropriate change.
12178  */
12179 void
12180 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12181 {
12182 	int options;
12183 	tcp_opt_t tcpopt;
12184 	uint32_t mss_max;
12185 	char *tmp_tcph;
12186 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12187 
12188 	tcpopt.tcp = NULL;
12189 	options = tcp_parse_options(tcph, &tcpopt);
12190 
12191 	/*
12192 	 * Process MSS option.  Note that MSS option value does not account
12193 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12194 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12195 	 * IPv6.
12196 	 */
12197 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12198 		if (tcp->tcp_ipversion == IPV4_VERSION)
12199 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12200 		else
12201 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12202 	} else {
12203 		if (tcp->tcp_ipversion == IPV4_VERSION)
12204 			mss_max = tcps->tcps_mss_max_ipv4;
12205 		else
12206 			mss_max = tcps->tcps_mss_max_ipv6;
12207 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12208 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12209 		else if (tcpopt.tcp_opt_mss > mss_max)
12210 			tcpopt.tcp_opt_mss = mss_max;
12211 	}
12212 
12213 	/* Process Window Scale option. */
12214 	if (options & TCP_OPT_WSCALE_PRESENT) {
12215 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12216 		tcp->tcp_snd_ws_ok = B_TRUE;
12217 	} else {
12218 		tcp->tcp_snd_ws = B_FALSE;
12219 		tcp->tcp_snd_ws_ok = B_FALSE;
12220 		tcp->tcp_rcv_ws = B_FALSE;
12221 	}
12222 
12223 	/* Process Timestamp option. */
12224 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12225 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12226 		tmp_tcph = (char *)tcp->tcp_tcph;
12227 
12228 		tcp->tcp_snd_ts_ok = B_TRUE;
12229 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12230 		tcp->tcp_last_rcv_lbolt = lbolt64;
12231 		ASSERT(OK_32PTR(tmp_tcph));
12232 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12233 
12234 		/* Fill in our template header with basic timestamp option. */
12235 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12236 		tmp_tcph[0] = TCPOPT_NOP;
12237 		tmp_tcph[1] = TCPOPT_NOP;
12238 		tmp_tcph[2] = TCPOPT_TSTAMP;
12239 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12240 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12241 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12242 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12243 	} else {
12244 		tcp->tcp_snd_ts_ok = B_FALSE;
12245 	}
12246 
12247 	/*
12248 	 * Process SACK options.  If SACK is enabled for this connection,
12249 	 * then allocate the SACK info structure.  Note the following ways
12250 	 * when tcp_snd_sack_ok is set to true.
12251 	 *
12252 	 * For active connection: in tcp_adapt_ire() called in
12253 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12254 	 * is checked.
12255 	 *
12256 	 * For passive connection: in tcp_adapt_ire() called in
12257 	 * tcp_accept_comm().
12258 	 *
12259 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12260 	 * That check makes sure that if we did not send a SACK OK option,
12261 	 * we will not enable SACK for this connection even though the other
12262 	 * side sends us SACK OK option.  For active connection, the SACK
12263 	 * info structure has already been allocated.  So we need to free
12264 	 * it if SACK is disabled.
12265 	 */
12266 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12267 	    (tcp->tcp_snd_sack_ok ||
12268 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12269 		/* This should be true only in the passive case. */
12270 		if (tcp->tcp_sack_info == NULL) {
12271 			ASSERT(TCP_IS_DETACHED(tcp));
12272 			tcp->tcp_sack_info =
12273 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12274 		}
12275 		if (tcp->tcp_sack_info == NULL) {
12276 			tcp->tcp_snd_sack_ok = B_FALSE;
12277 		} else {
12278 			tcp->tcp_snd_sack_ok = B_TRUE;
12279 			if (tcp->tcp_snd_ts_ok) {
12280 				tcp->tcp_max_sack_blk = 3;
12281 			} else {
12282 				tcp->tcp_max_sack_blk = 4;
12283 			}
12284 		}
12285 	} else {
12286 		/*
12287 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12288 		 * no SACK info will be used for this
12289 		 * connection.  This assumes that SACK usage
12290 		 * permission is negotiated.  This may need
12291 		 * to be changed once this is clarified.
12292 		 */
12293 		if (tcp->tcp_sack_info != NULL) {
12294 			ASSERT(tcp->tcp_notsack_list == NULL);
12295 			kmem_cache_free(tcp_sack_info_cache,
12296 			    tcp->tcp_sack_info);
12297 			tcp->tcp_sack_info = NULL;
12298 		}
12299 		tcp->tcp_snd_sack_ok = B_FALSE;
12300 	}
12301 
12302 	/*
12303 	 * Now we know the exact TCP/IP header length, subtract
12304 	 * that from tcp_mss to get our side's MSS.
12305 	 */
12306 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12307 	/*
12308 	 * Here we assume that the other side's header size will be equal to
12309 	 * our header size.  We calculate the real MSS accordingly.  Need to
12310 	 * take into additional stuffs IPsec puts in.
12311 	 *
12312 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12313 	 */
12314 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12315 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12316 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12317 
12318 	/*
12319 	 * Set MSS to the smaller one of both ends of the connection.
12320 	 * We should not have called tcp_mss_set() before, but our
12321 	 * side of the MSS should have been set to a proper value
12322 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12323 	 * STREAM head parameters properly.
12324 	 *
12325 	 * If we have a larger-than-16-bit window but the other side
12326 	 * didn't want to do window scale, tcp_rwnd_set() will take
12327 	 * care of that.
12328 	 */
12329 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12330 }
12331 
12332 /*
12333  * Sends the T_CONN_IND to the listener. The caller calls this
12334  * functions via squeue to get inside the listener's perimeter
12335  * once the 3 way hand shake is done a T_CONN_IND needs to be
12336  * sent. As an optimization, the caller can call this directly
12337  * if listener's perimeter is same as eager's.
12338  */
12339 /* ARGSUSED */
12340 void
12341 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12342 {
12343 	conn_t			*lconnp = (conn_t *)arg;
12344 	tcp_t			*listener = lconnp->conn_tcp;
12345 	tcp_t			*tcp;
12346 	struct T_conn_ind	*conn_ind;
12347 	ipaddr_t 		*addr_cache;
12348 	boolean_t		need_send_conn_ind = B_FALSE;
12349 	tcp_stack_t		*tcps = listener->tcp_tcps;
12350 
12351 	/* retrieve the eager */
12352 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12353 	ASSERT(conn_ind->OPT_offset != 0 &&
12354 	    conn_ind->OPT_length == sizeof (intptr_t));
12355 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12356 	    conn_ind->OPT_length);
12357 
12358 	/*
12359 	 * TLI/XTI applications will get confused by
12360 	 * sending eager as an option since it violates
12361 	 * the option semantics. So remove the eager as
12362 	 * option since TLI/XTI app doesn't need it anyway.
12363 	 */
12364 	if (!TCP_IS_SOCKET(listener)) {
12365 		conn_ind->OPT_length = 0;
12366 		conn_ind->OPT_offset = 0;
12367 	}
12368 	if (listener->tcp_state != TCPS_LISTEN) {
12369 		/*
12370 		 * If listener has closed, it would have caused a
12371 		 * a cleanup/blowoff to happen for the eager. We
12372 		 * just need to return.
12373 		 */
12374 		freemsg(mp);
12375 		return;
12376 	}
12377 
12378 
12379 	/*
12380 	 * if the conn_req_q is full defer passing up the
12381 	 * T_CONN_IND until space is availabe after t_accept()
12382 	 * processing
12383 	 */
12384 	mutex_enter(&listener->tcp_eager_lock);
12385 
12386 	/*
12387 	 * Take the eager out, if it is in the list of droppable eagers
12388 	 * as we are here because the 3W handshake is over.
12389 	 */
12390 	MAKE_UNDROPPABLE(tcp);
12391 
12392 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12393 		tcp_t *tail;
12394 
12395 		/*
12396 		 * The eager already has an extra ref put in tcp_rput_data
12397 		 * so that it stays till accept comes back even though it
12398 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12399 		 */
12400 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12401 		listener->tcp_conn_req_cnt_q0--;
12402 		listener->tcp_conn_req_cnt_q++;
12403 
12404 		/* Move from SYN_RCVD to ESTABLISHED list  */
12405 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12406 		    tcp->tcp_eager_prev_q0;
12407 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12408 		    tcp->tcp_eager_next_q0;
12409 		tcp->tcp_eager_prev_q0 = NULL;
12410 		tcp->tcp_eager_next_q0 = NULL;
12411 
12412 		/*
12413 		 * Insert at end of the queue because sockfs
12414 		 * sends down T_CONN_RES in chronological
12415 		 * order. Leaving the older conn indications
12416 		 * at front of the queue helps reducing search
12417 		 * time.
12418 		 */
12419 		tail = listener->tcp_eager_last_q;
12420 		if (tail != NULL)
12421 			tail->tcp_eager_next_q = tcp;
12422 		else
12423 			listener->tcp_eager_next_q = tcp;
12424 		listener->tcp_eager_last_q = tcp;
12425 		tcp->tcp_eager_next_q = NULL;
12426 		/*
12427 		 * Delay sending up the T_conn_ind until we are
12428 		 * done with the eager. Once we have have sent up
12429 		 * the T_conn_ind, the accept can potentially complete
12430 		 * any time and release the refhold we have on the eager.
12431 		 */
12432 		need_send_conn_ind = B_TRUE;
12433 	} else {
12434 		/*
12435 		 * Defer connection on q0 and set deferred
12436 		 * connection bit true
12437 		 */
12438 		tcp->tcp_conn_def_q0 = B_TRUE;
12439 
12440 		/* take tcp out of q0 ... */
12441 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12442 		    tcp->tcp_eager_next_q0;
12443 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12444 		    tcp->tcp_eager_prev_q0;
12445 
12446 		/* ... and place it at the end of q0 */
12447 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12448 		tcp->tcp_eager_next_q0 = listener;
12449 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12450 		listener->tcp_eager_prev_q0 = tcp;
12451 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12452 	}
12453 
12454 	/* we have timed out before */
12455 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12456 		tcp->tcp_syn_rcvd_timeout = 0;
12457 		listener->tcp_syn_rcvd_timeout--;
12458 		if (listener->tcp_syn_defense &&
12459 		    listener->tcp_syn_rcvd_timeout <=
12460 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12461 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12462 		    listener->tcp_last_rcv_lbolt)) {
12463 			/*
12464 			 * Turn off the defense mode if we
12465 			 * believe the SYN attack is over.
12466 			 */
12467 			listener->tcp_syn_defense = B_FALSE;
12468 			if (listener->tcp_ip_addr_cache) {
12469 				kmem_free((void *)listener->tcp_ip_addr_cache,
12470 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12471 				listener->tcp_ip_addr_cache = NULL;
12472 			}
12473 		}
12474 	}
12475 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12476 	if (addr_cache != NULL) {
12477 		/*
12478 		 * We have finished a 3-way handshake with this
12479 		 * remote host. This proves the IP addr is good.
12480 		 * Cache it!
12481 		 */
12482 		addr_cache[IP_ADDR_CACHE_HASH(
12483 		    tcp->tcp_remote)] = tcp->tcp_remote;
12484 	}
12485 	mutex_exit(&listener->tcp_eager_lock);
12486 	if (need_send_conn_ind)
12487 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12488 }
12489 
12490 /*
12491  * Send the newconn notification to ulp. The eager is blown off if the
12492  * notification fails.
12493  */
12494 static void
12495 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12496 {
12497 	if (IPCL_IS_NONSTR(lconnp)) {
12498 		cred_t	*cr;
12499 		pid_t	cpid;
12500 
12501 		cr = msg_getcred(mp, &cpid);
12502 
12503 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12504 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12505 		    lconnp->conn_tcp);
12506 
12507 		/* Keep the message around in case of a fallback to TPI */
12508 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12509 
12510 		/*
12511 		 * Notify the ULP about the newconn. It is guaranteed that no
12512 		 * tcp_accept() call will be made for the eager if the
12513 		 * notification fails, so it's safe to blow it off in that
12514 		 * case.
12515 		 *
12516 		 * The upper handle will be assigned when tcp_accept() is
12517 		 * called.
12518 		 */
12519 		if ((*lconnp->conn_upcalls->su_newconn)
12520 		    (lconnp->conn_upper_handle,
12521 		    (sock_lower_handle_t)econnp,
12522 		    &sock_tcp_downcalls, cr, cpid,
12523 		    &econnp->conn_upcalls) == NULL) {
12524 			/* Failed to allocate a socket */
12525 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12526 			    tcpEstabResets);
12527 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12528 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12529 		}
12530 	} else {
12531 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12532 	}
12533 }
12534 
12535 mblk_t *
12536 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12537     uint_t *ifindexp, ip6_pkt_t *ippp)
12538 {
12539 	ip_pktinfo_t	*pinfo;
12540 	ip6_t		*ip6h;
12541 	uchar_t		*rptr;
12542 	mblk_t		*first_mp = mp;
12543 	boolean_t	mctl_present = B_FALSE;
12544 	uint_t 		ifindex = 0;
12545 	ip6_pkt_t	ipp;
12546 	uint_t		ipvers;
12547 	uint_t		ip_hdr_len;
12548 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12549 
12550 	rptr = mp->b_rptr;
12551 	ASSERT(OK_32PTR(rptr));
12552 	ASSERT(tcp != NULL);
12553 	ipp.ipp_fields = 0;
12554 
12555 	switch DB_TYPE(mp) {
12556 	case M_CTL:
12557 		mp = mp->b_cont;
12558 		if (mp == NULL) {
12559 			freemsg(first_mp);
12560 			return (NULL);
12561 		}
12562 		if (DB_TYPE(mp) != M_DATA) {
12563 			freemsg(first_mp);
12564 			return (NULL);
12565 		}
12566 		mctl_present = B_TRUE;
12567 		break;
12568 	case M_DATA:
12569 		break;
12570 	default:
12571 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12572 		freemsg(mp);
12573 		return (NULL);
12574 	}
12575 	ipvers = IPH_HDR_VERSION(rptr);
12576 	if (ipvers == IPV4_VERSION) {
12577 		if (tcp == NULL) {
12578 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12579 			goto done;
12580 		}
12581 
12582 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12583 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12584 
12585 		/*
12586 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12587 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12588 		 */
12589 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12590 		    mctl_present) {
12591 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12592 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12593 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12594 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12595 				ipp.ipp_fields |= IPPF_IFINDEX;
12596 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12597 				ifindex = pinfo->ip_pkt_ifindex;
12598 			}
12599 			freeb(first_mp);
12600 			mctl_present = B_FALSE;
12601 		}
12602 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12603 	} else {
12604 		ip6h = (ip6_t *)rptr;
12605 
12606 		ASSERT(ipvers == IPV6_VERSION);
12607 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12608 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12609 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12610 
12611 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12612 			uint8_t	nexthdrp;
12613 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12614 
12615 			/* Look for ifindex information */
12616 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12617 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12618 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12619 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12620 					freemsg(first_mp);
12621 					return (NULL);
12622 				}
12623 
12624 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12625 					ASSERT(ip6i->ip6i_ifindex != 0);
12626 					ipp.ipp_fields |= IPPF_IFINDEX;
12627 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12628 					ifindex = ip6i->ip6i_ifindex;
12629 				}
12630 				rptr = (uchar_t *)&ip6i[1];
12631 				mp->b_rptr = rptr;
12632 				if (rptr == mp->b_wptr) {
12633 					mblk_t *mp1;
12634 					mp1 = mp->b_cont;
12635 					freeb(mp);
12636 					mp = mp1;
12637 					rptr = mp->b_rptr;
12638 				}
12639 				if (MBLKL(mp) < IPV6_HDR_LEN +
12640 				    sizeof (tcph_t)) {
12641 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12642 					freemsg(first_mp);
12643 					return (NULL);
12644 				}
12645 				ip6h = (ip6_t *)rptr;
12646 			}
12647 
12648 			/*
12649 			 * Find any potentially interesting extension headers
12650 			 * as well as the length of the IPv6 + extension
12651 			 * headers.
12652 			 */
12653 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12654 			/* Verify if this is a TCP packet */
12655 			if (nexthdrp != IPPROTO_TCP) {
12656 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12657 				freemsg(first_mp);
12658 				return (NULL);
12659 			}
12660 		} else {
12661 			ip_hdr_len = IPV6_HDR_LEN;
12662 		}
12663 	}
12664 
12665 done:
12666 	if (ipversp != NULL)
12667 		*ipversp = ipvers;
12668 	if (ip_hdr_lenp != NULL)
12669 		*ip_hdr_lenp = ip_hdr_len;
12670 	if (ippp != NULL)
12671 		*ippp = ipp;
12672 	if (ifindexp != NULL)
12673 		*ifindexp = ifindex;
12674 	if (mctl_present) {
12675 		freeb(first_mp);
12676 	}
12677 	return (mp);
12678 }
12679 
12680 /*
12681  * Handle M_DATA messages from IP. Its called directly from IP via
12682  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12683  * in this path.
12684  *
12685  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12686  * v4 and v6), we are called through tcp_input() and a M_CTL can
12687  * be present for options but tcp_find_pktinfo() deals with it. We
12688  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12689  *
12690  * The first argument is always the connp/tcp to which the mp belongs.
12691  * There are no exceptions to this rule. The caller has already put
12692  * a reference on this connp/tcp and once tcp_rput_data() returns,
12693  * the squeue will do the refrele.
12694  *
12695  * The TH_SYN for the listener directly go to tcp_conn_request via
12696  * squeue.
12697  *
12698  * sqp: NULL = recursive, sqp != NULL means called from squeue
12699  */
12700 void
12701 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12702 {
12703 	int32_t		bytes_acked;
12704 	int32_t		gap;
12705 	mblk_t		*mp1;
12706 	uint_t		flags;
12707 	uint32_t	new_swnd = 0;
12708 	uchar_t		*iphdr;
12709 	uchar_t		*rptr;
12710 	int32_t		rgap;
12711 	uint32_t	seg_ack;
12712 	int		seg_len;
12713 	uint_t		ip_hdr_len;
12714 	uint32_t	seg_seq;
12715 	tcph_t		*tcph;
12716 	int		urp;
12717 	tcp_opt_t	tcpopt;
12718 	uint_t		ipvers;
12719 	ip6_pkt_t	ipp;
12720 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12721 	uint32_t	cwnd;
12722 	uint32_t	add;
12723 	int		npkt;
12724 	int		mss;
12725 	conn_t		*connp = (conn_t *)arg;
12726 	squeue_t	*sqp = (squeue_t *)arg2;
12727 	tcp_t		*tcp = connp->conn_tcp;
12728 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12729 
12730 	/*
12731 	 * RST from fused tcp loopback peer should trigger an unfuse.
12732 	 */
12733 	if (tcp->tcp_fused) {
12734 		TCP_STAT(tcps, tcp_fusion_aborted);
12735 		tcp_unfuse(tcp);
12736 	}
12737 
12738 	iphdr = mp->b_rptr;
12739 	rptr = mp->b_rptr;
12740 	ASSERT(OK_32PTR(rptr));
12741 
12742 	/*
12743 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12744 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12745 	 * necessary information.
12746 	 */
12747 	if (IPCL_IS_TCP4(connp)) {
12748 		ipvers = IPV4_VERSION;
12749 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12750 	} else {
12751 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12752 		    NULL, &ipp);
12753 		if (mp == NULL) {
12754 			TCP_STAT(tcps, tcp_rput_v6_error);
12755 			return;
12756 		}
12757 		iphdr = mp->b_rptr;
12758 		rptr = mp->b_rptr;
12759 	}
12760 	ASSERT(DB_TYPE(mp) == M_DATA);
12761 	ASSERT(mp->b_next == NULL);
12762 
12763 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12764 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12765 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12766 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12767 	seg_len = (int)(mp->b_wptr - rptr) -
12768 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12769 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12770 		do {
12771 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12772 			    (uintptr_t)INT_MAX);
12773 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12774 		} while ((mp1 = mp1->b_cont) != NULL &&
12775 		    mp1->b_datap->db_type == M_DATA);
12776 	}
12777 
12778 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12779 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12780 		    seg_len, tcph);
12781 		return;
12782 	}
12783 
12784 	if (sqp != NULL) {
12785 		/*
12786 		 * This is the correct place to update tcp_last_recv_time. Note
12787 		 * that it is also updated for tcp structure that belongs to
12788 		 * global and listener queues which do not really need updating.
12789 		 * But that should not cause any harm.  And it is updated for
12790 		 * all kinds of incoming segments, not only for data segments.
12791 		 */
12792 		tcp->tcp_last_recv_time = lbolt;
12793 	}
12794 
12795 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12796 
12797 	BUMP_LOCAL(tcp->tcp_ibsegs);
12798 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12799 
12800 	if ((flags & TH_URG) && sqp != NULL) {
12801 		/*
12802 		 * TCP can't handle urgent pointers that arrive before
12803 		 * the connection has been accept()ed since it can't
12804 		 * buffer OOB data.  Discard segment if this happens.
12805 		 *
12806 		 * We can't just rely on a non-null tcp_listener to indicate
12807 		 * that the accept() has completed since unlinking of the
12808 		 * eager and completion of the accept are not atomic.
12809 		 * tcp_detached, when it is not set (B_FALSE) indicates
12810 		 * that the accept() has completed.
12811 		 *
12812 		 * Nor can it reassemble urgent pointers, so discard
12813 		 * if it's not the next segment expected.
12814 		 *
12815 		 * Otherwise, collapse chain into one mblk (discard if
12816 		 * that fails).  This makes sure the headers, retransmitted
12817 		 * data, and new data all are in the same mblk.
12818 		 */
12819 		ASSERT(mp != NULL);
12820 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12821 			freemsg(mp);
12822 			return;
12823 		}
12824 		/* Update pointers into message */
12825 		iphdr = rptr = mp->b_rptr;
12826 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12827 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12828 			/*
12829 			 * Since we can't handle any data with this urgent
12830 			 * pointer that is out of sequence, we expunge
12831 			 * the data.  This allows us to still register
12832 			 * the urgent mark and generate the M_PCSIG,
12833 			 * which we can do.
12834 			 */
12835 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12836 			seg_len = 0;
12837 		}
12838 	}
12839 
12840 	switch (tcp->tcp_state) {
12841 	case TCPS_SYN_SENT:
12842 		if (flags & TH_ACK) {
12843 			/*
12844 			 * Note that our stack cannot send data before a
12845 			 * connection is established, therefore the
12846 			 * following check is valid.  Otherwise, it has
12847 			 * to be changed.
12848 			 */
12849 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12850 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12851 				freemsg(mp);
12852 				if (flags & TH_RST)
12853 					return;
12854 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12855 				    tcp, seg_ack, 0, TH_RST);
12856 				return;
12857 			}
12858 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12859 		}
12860 		if (flags & TH_RST) {
12861 			freemsg(mp);
12862 			if (flags & TH_ACK)
12863 				(void) tcp_clean_death(tcp,
12864 				    ECONNREFUSED, 13);
12865 			return;
12866 		}
12867 		if (!(flags & TH_SYN)) {
12868 			freemsg(mp);
12869 			return;
12870 		}
12871 
12872 		/* Process all TCP options. */
12873 		tcp_process_options(tcp, tcph);
12874 		/*
12875 		 * The following changes our rwnd to be a multiple of the
12876 		 * MIN(peer MSS, our MSS) for performance reason.
12877 		 */
12878 		(void) tcp_rwnd_set(tcp,
12879 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
12880 
12881 		/* Is the other end ECN capable? */
12882 		if (tcp->tcp_ecn_ok) {
12883 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12884 				tcp->tcp_ecn_ok = B_FALSE;
12885 			}
12886 		}
12887 		/*
12888 		 * Clear ECN flags because it may interfere with later
12889 		 * processing.
12890 		 */
12891 		flags &= ~(TH_ECE|TH_CWR);
12892 
12893 		tcp->tcp_irs = seg_seq;
12894 		tcp->tcp_rack = seg_seq;
12895 		tcp->tcp_rnxt = seg_seq + 1;
12896 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12897 		if (!TCP_IS_DETACHED(tcp)) {
12898 			/* Allocate room for SACK options if needed. */
12899 			if (tcp->tcp_snd_sack_ok) {
12900 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12901 				    tcp->tcp_hdr_len +
12902 				    TCPOPT_MAX_SACK_LEN +
12903 				    (tcp->tcp_loopback ? 0 :
12904 				    tcps->tcps_wroff_xtra));
12905 			} else {
12906 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12907 				    tcp->tcp_hdr_len +
12908 				    (tcp->tcp_loopback ? 0 :
12909 				    tcps->tcps_wroff_xtra));
12910 			}
12911 		}
12912 		if (flags & TH_ACK) {
12913 			/*
12914 			 * If we can't get the confirmation upstream, pretend
12915 			 * we didn't even see this one.
12916 			 *
12917 			 * XXX: how can we pretend we didn't see it if we
12918 			 * have updated rnxt et. al.
12919 			 *
12920 			 * For loopback we defer sending up the T_CONN_CON
12921 			 * until after some checks below.
12922 			 */
12923 			mp1 = NULL;
12924 			/*
12925 			 * tcp_sendmsg() checks tcp_state without entering
12926 			 * the squeue so tcp_state should be updated before
12927 			 * sending up connection confirmation
12928 			 */
12929 			tcp->tcp_state = TCPS_ESTABLISHED;
12930 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12931 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12932 				tcp->tcp_state = TCPS_SYN_SENT;
12933 				freemsg(mp);
12934 				return;
12935 			}
12936 			/* SYN was acked - making progress */
12937 			if (tcp->tcp_ipversion == IPV6_VERSION)
12938 				tcp->tcp_ip_forward_progress = B_TRUE;
12939 
12940 			/* One for the SYN */
12941 			tcp->tcp_suna = tcp->tcp_iss + 1;
12942 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12943 
12944 			/*
12945 			 * If SYN was retransmitted, need to reset all
12946 			 * retransmission info.  This is because this
12947 			 * segment will be treated as a dup ACK.
12948 			 */
12949 			if (tcp->tcp_rexmit) {
12950 				tcp->tcp_rexmit = B_FALSE;
12951 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12952 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12953 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12954 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12955 				tcp->tcp_ms_we_have_waited = 0;
12956 
12957 				/*
12958 				 * Set tcp_cwnd back to 1 MSS, per
12959 				 * recommendation from
12960 				 * draft-floyd-incr-init-win-01.txt,
12961 				 * Increasing TCP's Initial Window.
12962 				 */
12963 				tcp->tcp_cwnd = tcp->tcp_mss;
12964 			}
12965 
12966 			tcp->tcp_swl1 = seg_seq;
12967 			tcp->tcp_swl2 = seg_ack;
12968 
12969 			new_swnd = BE16_TO_U16(tcph->th_win);
12970 			tcp->tcp_swnd = new_swnd;
12971 			if (new_swnd > tcp->tcp_max_swnd)
12972 				tcp->tcp_max_swnd = new_swnd;
12973 
12974 			/*
12975 			 * Always send the three-way handshake ack immediately
12976 			 * in order to make the connection complete as soon as
12977 			 * possible on the accepting host.
12978 			 */
12979 			flags |= TH_ACK_NEEDED;
12980 
12981 			/*
12982 			 * Special case for loopback.  At this point we have
12983 			 * received SYN-ACK from the remote endpoint.  In
12984 			 * order to ensure that both endpoints reach the
12985 			 * fused state prior to any data exchange, the final
12986 			 * ACK needs to be sent before we indicate T_CONN_CON
12987 			 * to the module upstream.
12988 			 */
12989 			if (tcp->tcp_loopback) {
12990 				mblk_t *ack_mp;
12991 
12992 				ASSERT(!tcp->tcp_unfusable);
12993 				ASSERT(mp1 != NULL);
12994 				/*
12995 				 * For loopback, we always get a pure SYN-ACK
12996 				 * and only need to send back the final ACK
12997 				 * with no data (this is because the other
12998 				 * tcp is ours and we don't do T/TCP).  This
12999 				 * final ACK triggers the passive side to
13000 				 * perform fusion in ESTABLISHED state.
13001 				 */
13002 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13003 					if (tcp->tcp_ack_tid != 0) {
13004 						(void) TCP_TIMER_CANCEL(tcp,
13005 						    tcp->tcp_ack_tid);
13006 						tcp->tcp_ack_tid = 0;
13007 					}
13008 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13009 					BUMP_LOCAL(tcp->tcp_obsegs);
13010 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13011 
13012 					if (!IPCL_IS_NONSTR(connp)) {
13013 						/* Send up T_CONN_CON */
13014 						putnext(tcp->tcp_rq, mp1);
13015 					} else {
13016 						cred_t	*cr;
13017 						pid_t	cpid;
13018 
13019 						cr = msg_getcred(mp1, &cpid);
13020 						(*connp->conn_upcalls->
13021 						    su_connected)
13022 						    (connp->conn_upper_handle,
13023 						    tcp->tcp_connid, cr, cpid);
13024 						freemsg(mp1);
13025 					}
13026 
13027 					freemsg(mp);
13028 					return;
13029 				}
13030 				/*
13031 				 * Forget fusion; we need to handle more
13032 				 * complex cases below.  Send the deferred
13033 				 * T_CONN_CON message upstream and proceed
13034 				 * as usual.  Mark this tcp as not capable
13035 				 * of fusion.
13036 				 */
13037 				TCP_STAT(tcps, tcp_fusion_unfusable);
13038 				tcp->tcp_unfusable = B_TRUE;
13039 				if (!IPCL_IS_NONSTR(connp)) {
13040 					putnext(tcp->tcp_rq, mp1);
13041 				} else {
13042 					cred_t	*cr;
13043 					pid_t	cpid;
13044 
13045 					cr = msg_getcred(mp1, &cpid);
13046 					(*connp->conn_upcalls->su_connected)
13047 					    (connp->conn_upper_handle,
13048 					    tcp->tcp_connid, cr, cpid);
13049 					freemsg(mp1);
13050 				}
13051 			}
13052 
13053 			/*
13054 			 * Check to see if there is data to be sent.  If
13055 			 * yes, set the transmit flag.  Then check to see
13056 			 * if received data processing needs to be done.
13057 			 * If not, go straight to xmit_check.  This short
13058 			 * cut is OK as we don't support T/TCP.
13059 			 */
13060 			if (tcp->tcp_unsent)
13061 				flags |= TH_XMIT_NEEDED;
13062 
13063 			if (seg_len == 0 && !(flags & TH_URG)) {
13064 				freemsg(mp);
13065 				goto xmit_check;
13066 			}
13067 
13068 			flags &= ~TH_SYN;
13069 			seg_seq++;
13070 			break;
13071 		}
13072 		tcp->tcp_state = TCPS_SYN_RCVD;
13073 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13074 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13075 		if (mp1) {
13076 			/*
13077 			 * See comment in tcp_conn_request() for why we use
13078 			 * the open() time pid here.
13079 			 */
13080 			DB_CPID(mp1) = tcp->tcp_cpid;
13081 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13082 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13083 		}
13084 		freemsg(mp);
13085 		return;
13086 	case TCPS_SYN_RCVD:
13087 		if (flags & TH_ACK) {
13088 			/*
13089 			 * In this state, a SYN|ACK packet is either bogus
13090 			 * because the other side must be ACKing our SYN which
13091 			 * indicates it has seen the ACK for their SYN and
13092 			 * shouldn't retransmit it or we're crossing SYNs
13093 			 * on active open.
13094 			 */
13095 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13096 				freemsg(mp);
13097 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13098 				    tcp, seg_ack, 0, TH_RST);
13099 				return;
13100 			}
13101 			/*
13102 			 * NOTE: RFC 793 pg. 72 says this should be
13103 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13104 			 * but that would mean we have an ack that ignored
13105 			 * our SYN.
13106 			 */
13107 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13108 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13109 				freemsg(mp);
13110 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13111 				    tcp, seg_ack, 0, TH_RST);
13112 				return;
13113 			}
13114 		}
13115 		break;
13116 	case TCPS_LISTEN:
13117 		/*
13118 		 * Only a TLI listener can come through this path when a
13119 		 * acceptor is going back to be a listener and a packet
13120 		 * for the acceptor hits the classifier. For a socket
13121 		 * listener, this can never happen because a listener
13122 		 * can never accept connection on itself and hence a
13123 		 * socket acceptor can not go back to being a listener.
13124 		 */
13125 		ASSERT(!TCP_IS_SOCKET(tcp));
13126 		/*FALLTHRU*/
13127 	case TCPS_CLOSED:
13128 	case TCPS_BOUND: {
13129 		conn_t	*new_connp;
13130 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13131 
13132 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13133 		if (new_connp != NULL) {
13134 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13135 			return;
13136 		}
13137 		/* We failed to classify. For now just drop the packet */
13138 		freemsg(mp);
13139 		return;
13140 	}
13141 	case TCPS_IDLE:
13142 		/*
13143 		 * Handle the case where the tcp_clean_death() has happened
13144 		 * on a connection (application hasn't closed yet) but a packet
13145 		 * was already queued on squeue before tcp_clean_death()
13146 		 * was processed. Calling tcp_clean_death() twice on same
13147 		 * connection can result in weird behaviour.
13148 		 */
13149 		freemsg(mp);
13150 		return;
13151 	default:
13152 		break;
13153 	}
13154 
13155 	/*
13156 	 * Already on the correct queue/perimeter.
13157 	 * If this is a detached connection and not an eager
13158 	 * connection hanging off a listener then new data
13159 	 * (past the FIN) will cause a reset.
13160 	 * We do a special check here where it
13161 	 * is out of the main line, rather than check
13162 	 * if we are detached every time we see new
13163 	 * data down below.
13164 	 */
13165 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13166 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13167 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13168 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13169 
13170 		freemsg(mp);
13171 		/*
13172 		 * This could be an SSL closure alert. We're detached so just
13173 		 * acknowledge it this last time.
13174 		 */
13175 		if (tcp->tcp_kssl_ctx != NULL) {
13176 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13177 			tcp->tcp_kssl_ctx = NULL;
13178 
13179 			tcp->tcp_rnxt += seg_len;
13180 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13181 			flags |= TH_ACK_NEEDED;
13182 			goto ack_check;
13183 		}
13184 
13185 		tcp_xmit_ctl("new data when detached", tcp,
13186 		    tcp->tcp_snxt, 0, TH_RST);
13187 		(void) tcp_clean_death(tcp, EPROTO, 12);
13188 		return;
13189 	}
13190 
13191 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13192 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13193 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13194 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13195 
13196 	if (tcp->tcp_snd_ts_ok) {
13197 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13198 			/*
13199 			 * This segment is not acceptable.
13200 			 * Drop it and send back an ACK.
13201 			 */
13202 			freemsg(mp);
13203 			flags |= TH_ACK_NEEDED;
13204 			goto ack_check;
13205 		}
13206 	} else if (tcp->tcp_snd_sack_ok) {
13207 		ASSERT(tcp->tcp_sack_info != NULL);
13208 		tcpopt.tcp = tcp;
13209 		/*
13210 		 * SACK info in already updated in tcp_parse_options.  Ignore
13211 		 * all other TCP options...
13212 		 */
13213 		(void) tcp_parse_options(tcph, &tcpopt);
13214 	}
13215 try_again:;
13216 	mss = tcp->tcp_mss;
13217 	gap = seg_seq - tcp->tcp_rnxt;
13218 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13219 	/*
13220 	 * gap is the amount of sequence space between what we expect to see
13221 	 * and what we got for seg_seq.  A positive value for gap means
13222 	 * something got lost.  A negative value means we got some old stuff.
13223 	 */
13224 	if (gap < 0) {
13225 		/* Old stuff present.  Is the SYN in there? */
13226 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13227 		    (seg_len != 0)) {
13228 			flags &= ~TH_SYN;
13229 			seg_seq++;
13230 			urp--;
13231 			/* Recompute the gaps after noting the SYN. */
13232 			goto try_again;
13233 		}
13234 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13235 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13236 		    (seg_len > -gap ? -gap : seg_len));
13237 		/* Remove the old stuff from seg_len. */
13238 		seg_len += gap;
13239 		/*
13240 		 * Anything left?
13241 		 * Make sure to check for unack'd FIN when rest of data
13242 		 * has been previously ack'd.
13243 		 */
13244 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13245 			/*
13246 			 * Resets are only valid if they lie within our offered
13247 			 * window.  If the RST bit is set, we just ignore this
13248 			 * segment.
13249 			 */
13250 			if (flags & TH_RST) {
13251 				freemsg(mp);
13252 				return;
13253 			}
13254 
13255 			/*
13256 			 * The arriving of dup data packets indicate that we
13257 			 * may have postponed an ack for too long, or the other
13258 			 * side's RTT estimate is out of shape. Start acking
13259 			 * more often.
13260 			 */
13261 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13262 			    tcp->tcp_rack_cnt >= 1 &&
13263 			    tcp->tcp_rack_abs_max > 2) {
13264 				tcp->tcp_rack_abs_max--;
13265 			}
13266 			tcp->tcp_rack_cur_max = 1;
13267 
13268 			/*
13269 			 * This segment is "unacceptable".  None of its
13270 			 * sequence space lies within our advertized window.
13271 			 *
13272 			 * Adjust seg_len to the original value for tracing.
13273 			 */
13274 			seg_len -= gap;
13275 			if (tcp->tcp_debug) {
13276 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13277 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13278 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13279 				    "seg_len %d, rnxt %u, snxt %u, %s",
13280 				    gap, rgap, flags, seg_seq, seg_ack,
13281 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13282 				    tcp_display(tcp, NULL,
13283 				    DISP_ADDR_AND_PORT));
13284 			}
13285 
13286 			/*
13287 			 * Arrange to send an ACK in response to the
13288 			 * unacceptable segment per RFC 793 page 69. There
13289 			 * is only one small difference between ours and the
13290 			 * acceptability test in the RFC - we accept ACK-only
13291 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13292 			 * will be generated.
13293 			 *
13294 			 * Note that we have to ACK an ACK-only packet at least
13295 			 * for stacks that send 0-length keep-alives with
13296 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13297 			 * section 4.2.3.6. As long as we don't ever generate
13298 			 * an unacceptable packet in response to an incoming
13299 			 * packet that is unacceptable, it should not cause
13300 			 * "ACK wars".
13301 			 */
13302 			flags |=  TH_ACK_NEEDED;
13303 
13304 			/*
13305 			 * Continue processing this segment in order to use the
13306 			 * ACK information it contains, but skip all other
13307 			 * sequence-number processing.	Processing the ACK
13308 			 * information is necessary in order to
13309 			 * re-synchronize connections that may have lost
13310 			 * synchronization.
13311 			 *
13312 			 * We clear seg_len and flag fields related to
13313 			 * sequence number processing as they are not
13314 			 * to be trusted for an unacceptable segment.
13315 			 */
13316 			seg_len = 0;
13317 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13318 			goto process_ack;
13319 		}
13320 
13321 		/* Fix seg_seq, and chew the gap off the front. */
13322 		seg_seq = tcp->tcp_rnxt;
13323 		urp += gap;
13324 		do {
13325 			mblk_t	*mp2;
13326 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13327 			    (uintptr_t)UINT_MAX);
13328 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13329 			if (gap > 0) {
13330 				mp->b_rptr = mp->b_wptr - gap;
13331 				break;
13332 			}
13333 			mp2 = mp;
13334 			mp = mp->b_cont;
13335 			freeb(mp2);
13336 		} while (gap < 0);
13337 		/*
13338 		 * If the urgent data has already been acknowledged, we
13339 		 * should ignore TH_URG below
13340 		 */
13341 		if (urp < 0)
13342 			flags &= ~TH_URG;
13343 	}
13344 	/*
13345 	 * rgap is the amount of stuff received out of window.  A negative
13346 	 * value is the amount out of window.
13347 	 */
13348 	if (rgap < 0) {
13349 		mblk_t	*mp2;
13350 
13351 		if (tcp->tcp_rwnd == 0) {
13352 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13353 		} else {
13354 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13355 			UPDATE_MIB(&tcps->tcps_mib,
13356 			    tcpInDataPastWinBytes, -rgap);
13357 		}
13358 
13359 		/*
13360 		 * seg_len does not include the FIN, so if more than
13361 		 * just the FIN is out of window, we act like we don't
13362 		 * see it.  (If just the FIN is out of window, rgap
13363 		 * will be zero and we will go ahead and acknowledge
13364 		 * the FIN.)
13365 		 */
13366 		flags &= ~TH_FIN;
13367 
13368 		/* Fix seg_len and make sure there is something left. */
13369 		seg_len += rgap;
13370 		if (seg_len <= 0) {
13371 			/*
13372 			 * Resets are only valid if they lie within our offered
13373 			 * window.  If the RST bit is set, we just ignore this
13374 			 * segment.
13375 			 */
13376 			if (flags & TH_RST) {
13377 				freemsg(mp);
13378 				return;
13379 			}
13380 
13381 			/* Per RFC 793, we need to send back an ACK. */
13382 			flags |= TH_ACK_NEEDED;
13383 
13384 			/*
13385 			 * Send SIGURG as soon as possible i.e. even
13386 			 * if the TH_URG was delivered in a window probe
13387 			 * packet (which will be unacceptable).
13388 			 *
13389 			 * We generate a signal if none has been generated
13390 			 * for this connection or if this is a new urgent
13391 			 * byte. Also send a zero-length "unmarked" message
13392 			 * to inform SIOCATMARK that this is not the mark.
13393 			 *
13394 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13395 			 * is sent up. This plus the check for old data
13396 			 * (gap >= 0) handles the wraparound of the sequence
13397 			 * number space without having to always track the
13398 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13399 			 * this max in its rcv_up variable).
13400 			 *
13401 			 * This prevents duplicate SIGURGS due to a "late"
13402 			 * zero-window probe when the T_EXDATA_IND has already
13403 			 * been sent up.
13404 			 */
13405 			if ((flags & TH_URG) &&
13406 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13407 			    tcp->tcp_urp_last))) {
13408 				if (IPCL_IS_NONSTR(connp)) {
13409 					if (!TCP_IS_DETACHED(tcp)) {
13410 						(*connp->conn_upcalls->
13411 						    su_signal_oob)
13412 						    (connp->conn_upper_handle,
13413 						    urp);
13414 					}
13415 				} else {
13416 					mp1 = allocb(0, BPRI_MED);
13417 					if (mp1 == NULL) {
13418 						freemsg(mp);
13419 						return;
13420 					}
13421 					if (!TCP_IS_DETACHED(tcp) &&
13422 					    !putnextctl1(tcp->tcp_rq,
13423 					    M_PCSIG, SIGURG)) {
13424 						/* Try again on the rexmit. */
13425 						freemsg(mp1);
13426 						freemsg(mp);
13427 						return;
13428 					}
13429 					/*
13430 					 * If the next byte would be the mark
13431 					 * then mark with MARKNEXT else mark
13432 					 * with NOTMARKNEXT.
13433 					 */
13434 					if (gap == 0 && urp == 0)
13435 						mp1->b_flag |= MSGMARKNEXT;
13436 					else
13437 						mp1->b_flag |= MSGNOTMARKNEXT;
13438 					freemsg(tcp->tcp_urp_mark_mp);
13439 					tcp->tcp_urp_mark_mp = mp1;
13440 					flags |= TH_SEND_URP_MARK;
13441 				}
13442 				tcp->tcp_urp_last_valid = B_TRUE;
13443 				tcp->tcp_urp_last = urp + seg_seq;
13444 			}
13445 			/*
13446 			 * If this is a zero window probe, continue to
13447 			 * process the ACK part.  But we need to set seg_len
13448 			 * to 0 to avoid data processing.  Otherwise just
13449 			 * drop the segment and send back an ACK.
13450 			 */
13451 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13452 				flags &= ~(TH_SYN | TH_URG);
13453 				seg_len = 0;
13454 				goto process_ack;
13455 			} else {
13456 				freemsg(mp);
13457 				goto ack_check;
13458 			}
13459 		}
13460 		/* Pitch out of window stuff off the end. */
13461 		rgap = seg_len;
13462 		mp2 = mp;
13463 		do {
13464 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13465 			    (uintptr_t)INT_MAX);
13466 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13467 			if (rgap < 0) {
13468 				mp2->b_wptr += rgap;
13469 				if ((mp1 = mp2->b_cont) != NULL) {
13470 					mp2->b_cont = NULL;
13471 					freemsg(mp1);
13472 				}
13473 				break;
13474 			}
13475 		} while ((mp2 = mp2->b_cont) != NULL);
13476 	}
13477 ok:;
13478 	/*
13479 	 * TCP should check ECN info for segments inside the window only.
13480 	 * Therefore the check should be done here.
13481 	 */
13482 	if (tcp->tcp_ecn_ok) {
13483 		if (flags & TH_CWR) {
13484 			tcp->tcp_ecn_echo_on = B_FALSE;
13485 		}
13486 		/*
13487 		 * Note that both ECN_CE and CWR can be set in the
13488 		 * same segment.  In this case, we once again turn
13489 		 * on ECN_ECHO.
13490 		 */
13491 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13492 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13493 
13494 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13495 				tcp->tcp_ecn_echo_on = B_TRUE;
13496 			}
13497 		} else {
13498 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13499 
13500 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13501 			    htonl(IPH_ECN_CE << 20)) {
13502 				tcp->tcp_ecn_echo_on = B_TRUE;
13503 			}
13504 		}
13505 	}
13506 
13507 	/*
13508 	 * Check whether we can update tcp_ts_recent.  This test is
13509 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13510 	 * Extensions for High Performance: An Update", Internet Draft.
13511 	 */
13512 	if (tcp->tcp_snd_ts_ok &&
13513 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13514 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13515 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13516 		tcp->tcp_last_rcv_lbolt = lbolt64;
13517 	}
13518 
13519 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13520 		/*
13521 		 * FIN in an out of order segment.  We record this in
13522 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13523 		 * Clear the FIN so that any check on FIN flag will fail.
13524 		 * Remember that FIN also counts in the sequence number
13525 		 * space.  So we need to ack out of order FIN only segments.
13526 		 */
13527 		if (flags & TH_FIN) {
13528 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13529 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13530 			flags &= ~TH_FIN;
13531 			flags |= TH_ACK_NEEDED;
13532 		}
13533 		if (seg_len > 0) {
13534 			/* Fill in the SACK blk list. */
13535 			if (tcp->tcp_snd_sack_ok) {
13536 				ASSERT(tcp->tcp_sack_info != NULL);
13537 				tcp_sack_insert(tcp->tcp_sack_list,
13538 				    seg_seq, seg_seq + seg_len,
13539 				    &(tcp->tcp_num_sack_blk));
13540 			}
13541 
13542 			/*
13543 			 * Attempt reassembly and see if we have something
13544 			 * ready to go.
13545 			 */
13546 			mp = tcp_reass(tcp, mp, seg_seq);
13547 			/* Always ack out of order packets */
13548 			flags |= TH_ACK_NEEDED | TH_PUSH;
13549 			if (mp) {
13550 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13551 				    (uintptr_t)INT_MAX);
13552 				seg_len = mp->b_cont ? msgdsize(mp) :
13553 				    (int)(mp->b_wptr - mp->b_rptr);
13554 				seg_seq = tcp->tcp_rnxt;
13555 				/*
13556 				 * A gap is filled and the seq num and len
13557 				 * of the gap match that of a previously
13558 				 * received FIN, put the FIN flag back in.
13559 				 */
13560 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13561 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13562 					flags |= TH_FIN;
13563 					tcp->tcp_valid_bits &=
13564 					    ~TCP_OFO_FIN_VALID;
13565 				}
13566 			} else {
13567 				/*
13568 				 * Keep going even with NULL mp.
13569 				 * There may be a useful ACK or something else
13570 				 * we don't want to miss.
13571 				 *
13572 				 * But TCP should not perform fast retransmit
13573 				 * because of the ack number.  TCP uses
13574 				 * seg_len == 0 to determine if it is a pure
13575 				 * ACK.  And this is not a pure ACK.
13576 				 */
13577 				seg_len = 0;
13578 				ofo_seg = B_TRUE;
13579 			}
13580 		}
13581 	} else if (seg_len > 0) {
13582 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13583 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13584 		/*
13585 		 * If an out of order FIN was received before, and the seq
13586 		 * num and len of the new segment match that of the FIN,
13587 		 * put the FIN flag back in.
13588 		 */
13589 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13590 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13591 			flags |= TH_FIN;
13592 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13593 		}
13594 	}
13595 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13596 	if (flags & TH_RST) {
13597 		freemsg(mp);
13598 		switch (tcp->tcp_state) {
13599 		case TCPS_SYN_RCVD:
13600 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13601 			break;
13602 		case TCPS_ESTABLISHED:
13603 		case TCPS_FIN_WAIT_1:
13604 		case TCPS_FIN_WAIT_2:
13605 		case TCPS_CLOSE_WAIT:
13606 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13607 			break;
13608 		case TCPS_CLOSING:
13609 		case TCPS_LAST_ACK:
13610 			(void) tcp_clean_death(tcp, 0, 16);
13611 			break;
13612 		default:
13613 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13614 			(void) tcp_clean_death(tcp, ENXIO, 17);
13615 			break;
13616 		}
13617 		return;
13618 	}
13619 	if (flags & TH_SYN) {
13620 		/*
13621 		 * See RFC 793, Page 71
13622 		 *
13623 		 * The seq number must be in the window as it should
13624 		 * be "fixed" above.  If it is outside window, it should
13625 		 * be already rejected.  Note that we allow seg_seq to be
13626 		 * rnxt + rwnd because we want to accept 0 window probe.
13627 		 */
13628 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13629 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13630 		freemsg(mp);
13631 		/*
13632 		 * If the ACK flag is not set, just use our snxt as the
13633 		 * seq number of the RST segment.
13634 		 */
13635 		if (!(flags & TH_ACK)) {
13636 			seg_ack = tcp->tcp_snxt;
13637 		}
13638 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13639 		    TH_RST|TH_ACK);
13640 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13641 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13642 		return;
13643 	}
13644 	/*
13645 	 * urp could be -1 when the urp field in the packet is 0
13646 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13647 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13648 	 */
13649 	if (flags & TH_URG && urp >= 0) {
13650 		if (!tcp->tcp_urp_last_valid ||
13651 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13652 			/*
13653 			 * Non-STREAMS sockets handle the urgent data a litte
13654 			 * differently from STREAMS based sockets. There is no
13655 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
13656 			 * flags to keep SIOCATMARK happy. Instead a
13657 			 * su_signal_oob upcall is made to update the mark.
13658 			 * Neither is a T_EXDATA_IND mblk needed to be
13659 			 * prepended to the urgent data. The urgent data is
13660 			 * delivered using the su_recv upcall, where we set
13661 			 * the MSG_OOB flag to indicate that it is urg data.
13662 			 *
13663 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
13664 			 * are used by non-STREAMS sockets.
13665 			 */
13666 			if (IPCL_IS_NONSTR(connp)) {
13667 				if (!TCP_IS_DETACHED(tcp)) {
13668 					(*connp->conn_upcalls->su_signal_oob)
13669 					    (connp->conn_upper_handle, urp);
13670 				}
13671 			} else {
13672 				/*
13673 				 * If we haven't generated the signal yet for
13674 				 * this urgent pointer value, do it now.  Also,
13675 				 * send up a zero-length M_DATA indicating
13676 				 * whether or not this is the mark. The latter
13677 				 * is not needed when a T_EXDATA_IND is sent up.
13678 				 * However, if there are allocation failures
13679 				 * this code relies on the sender retransmitting
13680 				 * and the socket code for determining the mark
13681 				 * should not block waiting for the peer to
13682 				 * transmit. Thus, for simplicity we always
13683 				 * send up the mark indication.
13684 				 */
13685 				mp1 = allocb(0, BPRI_MED);
13686 				if (mp1 == NULL) {
13687 					freemsg(mp);
13688 					return;
13689 				}
13690 				if (!TCP_IS_DETACHED(tcp) &&
13691 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13692 				    SIGURG)) {
13693 					/* Try again on the rexmit. */
13694 					freemsg(mp1);
13695 					freemsg(mp);
13696 					return;
13697 				}
13698 				/*
13699 				 * Mark with NOTMARKNEXT for now.
13700 				 * The code below will change this to MARKNEXT
13701 				 * if we are at the mark.
13702 				 *
13703 				 * If there are allocation failures (e.g. in
13704 				 * dupmsg below) the next time tcp_rput_data
13705 				 * sees the urgent segment it will send up the
13706 				 * MSGMARKNEXT message.
13707 				 */
13708 				mp1->b_flag |= MSGNOTMARKNEXT;
13709 				freemsg(tcp->tcp_urp_mark_mp);
13710 				tcp->tcp_urp_mark_mp = mp1;
13711 				flags |= TH_SEND_URP_MARK;
13712 #ifdef DEBUG
13713 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13714 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13715 				    "last %x, %s",
13716 				    seg_seq, urp, tcp->tcp_urp_last,
13717 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13718 #endif /* DEBUG */
13719 			}
13720 			tcp->tcp_urp_last_valid = B_TRUE;
13721 			tcp->tcp_urp_last = urp + seg_seq;
13722 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13723 			/*
13724 			 * An allocation failure prevented the previous
13725 			 * tcp_rput_data from sending up the allocated
13726 			 * MSG*MARKNEXT message - send it up this time
13727 			 * around.
13728 			 */
13729 			flags |= TH_SEND_URP_MARK;
13730 		}
13731 
13732 		/*
13733 		 * If the urgent byte is in this segment, make sure that it is
13734 		 * all by itself.  This makes it much easier to deal with the
13735 		 * possibility of an allocation failure on the T_exdata_ind.
13736 		 * Note that seg_len is the number of bytes in the segment, and
13737 		 * urp is the offset into the segment of the urgent byte.
13738 		 * urp < seg_len means that the urgent byte is in this segment.
13739 		 */
13740 		if (urp < seg_len) {
13741 			if (seg_len != 1) {
13742 				uint32_t  tmp_rnxt;
13743 				/*
13744 				 * Break it up and feed it back in.
13745 				 * Re-attach the IP header.
13746 				 */
13747 				mp->b_rptr = iphdr;
13748 				if (urp > 0) {
13749 					/*
13750 					 * There is stuff before the urgent
13751 					 * byte.
13752 					 */
13753 					mp1 = dupmsg(mp);
13754 					if (!mp1) {
13755 						/*
13756 						 * Trim from urgent byte on.
13757 						 * The rest will come back.
13758 						 */
13759 						(void) adjmsg(mp,
13760 						    urp - seg_len);
13761 						tcp_rput_data(connp,
13762 						    mp, NULL);
13763 						return;
13764 					}
13765 					(void) adjmsg(mp1, urp - seg_len);
13766 					/* Feed this piece back in. */
13767 					tmp_rnxt = tcp->tcp_rnxt;
13768 					tcp_rput_data(connp, mp1, NULL);
13769 					/*
13770 					 * If the data passed back in was not
13771 					 * processed (ie: bad ACK) sending
13772 					 * the remainder back in will cause a
13773 					 * loop. In this case, drop the
13774 					 * packet and let the sender try
13775 					 * sending a good packet.
13776 					 */
13777 					if (tmp_rnxt == tcp->tcp_rnxt) {
13778 						freemsg(mp);
13779 						return;
13780 					}
13781 				}
13782 				if (urp != seg_len - 1) {
13783 					uint32_t  tmp_rnxt;
13784 					/*
13785 					 * There is stuff after the urgent
13786 					 * byte.
13787 					 */
13788 					mp1 = dupmsg(mp);
13789 					if (!mp1) {
13790 						/*
13791 						 * Trim everything beyond the
13792 						 * urgent byte.  The rest will
13793 						 * come back.
13794 						 */
13795 						(void) adjmsg(mp,
13796 						    urp + 1 - seg_len);
13797 						tcp_rput_data(connp,
13798 						    mp, NULL);
13799 						return;
13800 					}
13801 					(void) adjmsg(mp1, urp + 1 - seg_len);
13802 					tmp_rnxt = tcp->tcp_rnxt;
13803 					tcp_rput_data(connp, mp1, NULL);
13804 					/*
13805 					 * If the data passed back in was not
13806 					 * processed (ie: bad ACK) sending
13807 					 * the remainder back in will cause a
13808 					 * loop. In this case, drop the
13809 					 * packet and let the sender try
13810 					 * sending a good packet.
13811 					 */
13812 					if (tmp_rnxt == tcp->tcp_rnxt) {
13813 						freemsg(mp);
13814 						return;
13815 					}
13816 				}
13817 				tcp_rput_data(connp, mp, NULL);
13818 				return;
13819 			}
13820 			/*
13821 			 * This segment contains only the urgent byte.  We
13822 			 * have to allocate the T_exdata_ind, if we can.
13823 			 */
13824 			if (IPCL_IS_NONSTR(connp)) {
13825 				int error;
13826 
13827 				(*connp->conn_upcalls->su_recv)
13828 				    (connp->conn_upper_handle, mp, seg_len,
13829 				    MSG_OOB, &error, NULL);
13830 				/*
13831 				 * We should never be in middle of a
13832 				 * fallback, the squeue guarantees that.
13833 				 */
13834 				ASSERT(error != EOPNOTSUPP);
13835 				mp = NULL;
13836 				goto update_ack;
13837 			} else if (!tcp->tcp_urp_mp) {
13838 				struct T_exdata_ind *tei;
13839 				mp1 = allocb(sizeof (struct T_exdata_ind),
13840 				    BPRI_MED);
13841 				if (!mp1) {
13842 					/*
13843 					 * Sigh... It'll be back.
13844 					 * Generate any MSG*MARK message now.
13845 					 */
13846 					freemsg(mp);
13847 					seg_len = 0;
13848 					if (flags & TH_SEND_URP_MARK) {
13849 
13850 
13851 						ASSERT(tcp->tcp_urp_mark_mp);
13852 						tcp->tcp_urp_mark_mp->b_flag &=
13853 						    ~MSGNOTMARKNEXT;
13854 						tcp->tcp_urp_mark_mp->b_flag |=
13855 						    MSGMARKNEXT;
13856 					}
13857 					goto ack_check;
13858 				}
13859 				mp1->b_datap->db_type = M_PROTO;
13860 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13861 				tei->PRIM_type = T_EXDATA_IND;
13862 				tei->MORE_flag = 0;
13863 				mp1->b_wptr = (uchar_t *)&tei[1];
13864 				tcp->tcp_urp_mp = mp1;
13865 #ifdef DEBUG
13866 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13867 				    "tcp_rput: allocated exdata_ind %s",
13868 				    tcp_display(tcp, NULL,
13869 				    DISP_PORT_ONLY));
13870 #endif /* DEBUG */
13871 				/*
13872 				 * There is no need to send a separate MSG*MARK
13873 				 * message since the T_EXDATA_IND will be sent
13874 				 * now.
13875 				 */
13876 				flags &= ~TH_SEND_URP_MARK;
13877 				freemsg(tcp->tcp_urp_mark_mp);
13878 				tcp->tcp_urp_mark_mp = NULL;
13879 			}
13880 			/*
13881 			 * Now we are all set.  On the next putnext upstream,
13882 			 * tcp_urp_mp will be non-NULL and will get prepended
13883 			 * to what has to be this piece containing the urgent
13884 			 * byte.  If for any reason we abort this segment below,
13885 			 * if it comes back, we will have this ready, or it
13886 			 * will get blown off in close.
13887 			 */
13888 		} else if (urp == seg_len) {
13889 			/*
13890 			 * The urgent byte is the next byte after this sequence
13891 			 * number. If this endpoint is non-STREAMS, then there
13892 			 * is nothing to do here since the socket has already
13893 			 * been notified about the urg pointer by the
13894 			 * su_signal_oob call above.
13895 			 *
13896 			 * In case of STREAMS, some more work might be needed.
13897 			 * If there is data it is marked with MSGMARKNEXT and
13898 			 * and any tcp_urp_mark_mp is discarded since it is not
13899 			 * needed. Otherwise, if the code above just allocated
13900 			 * a zero-length tcp_urp_mark_mp message, that message
13901 			 * is tagged with MSGMARKNEXT. Sending up these
13902 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
13903 			 * even though the T_EXDATA_IND will not be sent up
13904 			 * until the urgent byte arrives.
13905 			 */
13906 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
13907 				if (seg_len != 0) {
13908 					flags |= TH_MARKNEXT_NEEDED;
13909 					freemsg(tcp->tcp_urp_mark_mp);
13910 					tcp->tcp_urp_mark_mp = NULL;
13911 					flags &= ~TH_SEND_URP_MARK;
13912 				} else if (tcp->tcp_urp_mark_mp != NULL) {
13913 					flags |= TH_SEND_URP_MARK;
13914 					tcp->tcp_urp_mark_mp->b_flag &=
13915 					    ~MSGNOTMARKNEXT;
13916 					tcp->tcp_urp_mark_mp->b_flag |=
13917 					    MSGMARKNEXT;
13918 				}
13919 			}
13920 #ifdef DEBUG
13921 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13922 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13923 			    seg_len, flags,
13924 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13925 #endif /* DEBUG */
13926 		}
13927 #ifdef DEBUG
13928 		else {
13929 			/* Data left until we hit mark */
13930 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13931 			    "tcp_rput: URP %d bytes left, %s",
13932 			    urp - seg_len, tcp_display(tcp, NULL,
13933 			    DISP_PORT_ONLY));
13934 		}
13935 #endif /* DEBUG */
13936 	}
13937 
13938 process_ack:
13939 	if (!(flags & TH_ACK)) {
13940 		freemsg(mp);
13941 		goto xmit_check;
13942 	}
13943 	}
13944 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13945 
13946 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13947 		tcp->tcp_ip_forward_progress = B_TRUE;
13948 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13949 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13950 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13951 			/* 3-way handshake complete - pass up the T_CONN_IND */
13952 			tcp_t	*listener = tcp->tcp_listener;
13953 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13954 
13955 			tcp->tcp_tconnind_started = B_TRUE;
13956 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13957 			/*
13958 			 * We are here means eager is fine but it can
13959 			 * get a TH_RST at any point between now and till
13960 			 * accept completes and disappear. We need to
13961 			 * ensure that reference to eager is valid after
13962 			 * we get out of eager's perimeter. So we do
13963 			 * an extra refhold.
13964 			 */
13965 			CONN_INC_REF(connp);
13966 
13967 			/*
13968 			 * The listener also exists because of the refhold
13969 			 * done in tcp_conn_request. Its possible that it
13970 			 * might have closed. We will check that once we
13971 			 * get inside listeners context.
13972 			 */
13973 			CONN_INC_REF(listener->tcp_connp);
13974 			if (listener->tcp_connp->conn_sqp ==
13975 			    connp->conn_sqp) {
13976 				/*
13977 				 * We optimize by not calling an SQUEUE_ENTER
13978 				 * on the listener since we know that the
13979 				 * listener and eager squeues are the same.
13980 				 * We are able to make this check safely only
13981 				 * because neither the eager nor the listener
13982 				 * can change its squeue. Only an active connect
13983 				 * can change its squeue
13984 				 */
13985 				tcp_send_conn_ind(listener->tcp_connp, mp,
13986 				    listener->tcp_connp->conn_sqp);
13987 				CONN_DEC_REF(listener->tcp_connp);
13988 			} else if (!tcp->tcp_loopback) {
13989 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
13990 				    mp, tcp_send_conn_ind,
13991 				    listener->tcp_connp, SQ_FILL,
13992 				    SQTAG_TCP_CONN_IND);
13993 			} else {
13994 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
13995 				    mp, tcp_send_conn_ind,
13996 				    listener->tcp_connp, SQ_PROCESS,
13997 				    SQTAG_TCP_CONN_IND);
13998 			}
13999 		}
14000 
14001 		/*
14002 		 * We are seeing the final ack in the three way
14003 		 * hand shake of a active open'ed connection
14004 		 * so we must send up a T_CONN_CON
14005 		 *
14006 		 * tcp_sendmsg() checks tcp_state without entering
14007 		 * the squeue so tcp_state should be updated before
14008 		 * sending up connection confirmation.
14009 		 */
14010 		tcp->tcp_state = TCPS_ESTABLISHED;
14011 		if (tcp->tcp_active_open) {
14012 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14013 				freemsg(mp);
14014 				tcp->tcp_state = TCPS_SYN_RCVD;
14015 				return;
14016 			}
14017 			/*
14018 			 * Don't fuse the loopback endpoints for
14019 			 * simultaneous active opens.
14020 			 */
14021 			if (tcp->tcp_loopback) {
14022 				TCP_STAT(tcps, tcp_fusion_unfusable);
14023 				tcp->tcp_unfusable = B_TRUE;
14024 			}
14025 		}
14026 
14027 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14028 		bytes_acked--;
14029 		/* SYN was acked - making progress */
14030 		if (tcp->tcp_ipversion == IPV6_VERSION)
14031 			tcp->tcp_ip_forward_progress = B_TRUE;
14032 
14033 		/*
14034 		 * If SYN was retransmitted, need to reset all
14035 		 * retransmission info as this segment will be
14036 		 * treated as a dup ACK.
14037 		 */
14038 		if (tcp->tcp_rexmit) {
14039 			tcp->tcp_rexmit = B_FALSE;
14040 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14041 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14042 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14043 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14044 			tcp->tcp_ms_we_have_waited = 0;
14045 			tcp->tcp_cwnd = mss;
14046 		}
14047 
14048 		/*
14049 		 * We set the send window to zero here.
14050 		 * This is needed if there is data to be
14051 		 * processed already on the queue.
14052 		 * Later (at swnd_update label), the
14053 		 * "new_swnd > tcp_swnd" condition is satisfied
14054 		 * the XMIT_NEEDED flag is set in the current
14055 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14056 		 * called if there is already data on queue in
14057 		 * this state.
14058 		 */
14059 		tcp->tcp_swnd = 0;
14060 
14061 		if (new_swnd > tcp->tcp_max_swnd)
14062 			tcp->tcp_max_swnd = new_swnd;
14063 		tcp->tcp_swl1 = seg_seq;
14064 		tcp->tcp_swl2 = seg_ack;
14065 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14066 
14067 		/* Fuse when both sides are in ESTABLISHED state */
14068 		if (tcp->tcp_loopback && do_tcp_fusion)
14069 			tcp_fuse(tcp, iphdr, tcph);
14070 
14071 	}
14072 	/* This code follows 4.4BSD-Lite2 mostly. */
14073 	if (bytes_acked < 0)
14074 		goto est;
14075 
14076 	/*
14077 	 * If TCP is ECN capable and the congestion experience bit is
14078 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14079 	 * done once per window (or more loosely, per RTT).
14080 	 */
14081 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14082 		tcp->tcp_cwr = B_FALSE;
14083 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14084 		if (!tcp->tcp_cwr) {
14085 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14086 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14087 			tcp->tcp_cwnd = npkt * mss;
14088 			/*
14089 			 * If the cwnd is 0, use the timer to clock out
14090 			 * new segments.  This is required by the ECN spec.
14091 			 */
14092 			if (npkt == 0) {
14093 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14094 				/*
14095 				 * This makes sure that when the ACK comes
14096 				 * back, we will increase tcp_cwnd by 1 MSS.
14097 				 */
14098 				tcp->tcp_cwnd_cnt = 0;
14099 			}
14100 			tcp->tcp_cwr = B_TRUE;
14101 			/*
14102 			 * This marks the end of the current window of in
14103 			 * flight data.  That is why we don't use
14104 			 * tcp_suna + tcp_swnd.  Only data in flight can
14105 			 * provide ECN info.
14106 			 */
14107 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14108 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14109 		}
14110 	}
14111 
14112 	mp1 = tcp->tcp_xmit_head;
14113 	if (bytes_acked == 0) {
14114 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14115 			int dupack_cnt;
14116 
14117 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14118 			/*
14119 			 * Fast retransmit.  When we have seen exactly three
14120 			 * identical ACKs while we have unacked data
14121 			 * outstanding we take it as a hint that our peer
14122 			 * dropped something.
14123 			 *
14124 			 * If TCP is retransmitting, don't do fast retransmit.
14125 			 */
14126 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14127 			    ! tcp->tcp_rexmit) {
14128 				/* Do Limited Transmit */
14129 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14130 				    tcps->tcps_dupack_fast_retransmit) {
14131 					/*
14132 					 * RFC 3042
14133 					 *
14134 					 * What we need to do is temporarily
14135 					 * increase tcp_cwnd so that new
14136 					 * data can be sent if it is allowed
14137 					 * by the receive window (tcp_rwnd).
14138 					 * tcp_wput_data() will take care of
14139 					 * the rest.
14140 					 *
14141 					 * If the connection is SACK capable,
14142 					 * only do limited xmit when there
14143 					 * is SACK info.
14144 					 *
14145 					 * Note how tcp_cwnd is incremented.
14146 					 * The first dup ACK will increase
14147 					 * it by 1 MSS.  The second dup ACK
14148 					 * will increase it by 2 MSS.  This
14149 					 * means that only 1 new segment will
14150 					 * be sent for each dup ACK.
14151 					 */
14152 					if (tcp->tcp_unsent > 0 &&
14153 					    (!tcp->tcp_snd_sack_ok ||
14154 					    (tcp->tcp_snd_sack_ok &&
14155 					    tcp->tcp_notsack_list != NULL))) {
14156 						tcp->tcp_cwnd += mss <<
14157 						    (tcp->tcp_dupack_cnt - 1);
14158 						flags |= TH_LIMIT_XMIT;
14159 					}
14160 				} else if (dupack_cnt ==
14161 				    tcps->tcps_dupack_fast_retransmit) {
14162 
14163 				/*
14164 				 * If we have reduced tcp_ssthresh
14165 				 * because of ECN, do not reduce it again
14166 				 * unless it is already one window of data
14167 				 * away.  After one window of data, tcp_cwr
14168 				 * should then be cleared.  Note that
14169 				 * for non ECN capable connection, tcp_cwr
14170 				 * should always be false.
14171 				 *
14172 				 * Adjust cwnd since the duplicate
14173 				 * ack indicates that a packet was
14174 				 * dropped (due to congestion.)
14175 				 */
14176 				if (!tcp->tcp_cwr) {
14177 					npkt = ((tcp->tcp_snxt -
14178 					    tcp->tcp_suna) >> 1) / mss;
14179 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14180 					    mss;
14181 					tcp->tcp_cwnd = (npkt +
14182 					    tcp->tcp_dupack_cnt) * mss;
14183 				}
14184 				if (tcp->tcp_ecn_ok) {
14185 					tcp->tcp_cwr = B_TRUE;
14186 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14187 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14188 				}
14189 
14190 				/*
14191 				 * We do Hoe's algorithm.  Refer to her
14192 				 * paper "Improving the Start-up Behavior
14193 				 * of a Congestion Control Scheme for TCP,"
14194 				 * appeared in SIGCOMM'96.
14195 				 *
14196 				 * Save highest seq no we have sent so far.
14197 				 * Be careful about the invisible FIN byte.
14198 				 */
14199 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14200 				    (tcp->tcp_unsent == 0)) {
14201 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14202 				} else {
14203 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14204 				}
14205 
14206 				/*
14207 				 * Do not allow bursty traffic during.
14208 				 * fast recovery.  Refer to Fall and Floyd's
14209 				 * paper "Simulation-based Comparisons of
14210 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14211 				 * This is a best current practise.
14212 				 */
14213 				tcp->tcp_snd_burst = TCP_CWND_SS;
14214 
14215 				/*
14216 				 * For SACK:
14217 				 * Calculate tcp_pipe, which is the
14218 				 * estimated number of bytes in
14219 				 * network.
14220 				 *
14221 				 * tcp_fack is the highest sack'ed seq num
14222 				 * TCP has received.
14223 				 *
14224 				 * tcp_pipe is explained in the above quoted
14225 				 * Fall and Floyd's paper.  tcp_fack is
14226 				 * explained in Mathis and Mahdavi's
14227 				 * "Forward Acknowledgment: Refining TCP
14228 				 * Congestion Control" in SIGCOMM '96.
14229 				 */
14230 				if (tcp->tcp_snd_sack_ok) {
14231 					ASSERT(tcp->tcp_sack_info != NULL);
14232 					if (tcp->tcp_notsack_list != NULL) {
14233 						tcp->tcp_pipe = tcp->tcp_snxt -
14234 						    tcp->tcp_fack;
14235 						tcp->tcp_sack_snxt = seg_ack;
14236 						flags |= TH_NEED_SACK_REXMIT;
14237 					} else {
14238 						/*
14239 						 * Always initialize tcp_pipe
14240 						 * even though we don't have
14241 						 * any SACK info.  If later
14242 						 * we get SACK info and
14243 						 * tcp_pipe is not initialized,
14244 						 * funny things will happen.
14245 						 */
14246 						tcp->tcp_pipe =
14247 						    tcp->tcp_cwnd_ssthresh;
14248 					}
14249 				} else {
14250 					flags |= TH_REXMIT_NEEDED;
14251 				} /* tcp_snd_sack_ok */
14252 
14253 				} else {
14254 					/*
14255 					 * Here we perform congestion
14256 					 * avoidance, but NOT slow start.
14257 					 * This is known as the Fast
14258 					 * Recovery Algorithm.
14259 					 */
14260 					if (tcp->tcp_snd_sack_ok &&
14261 					    tcp->tcp_notsack_list != NULL) {
14262 						flags |= TH_NEED_SACK_REXMIT;
14263 						tcp->tcp_pipe -= mss;
14264 						if (tcp->tcp_pipe < 0)
14265 							tcp->tcp_pipe = 0;
14266 					} else {
14267 					/*
14268 					 * We know that one more packet has
14269 					 * left the pipe thus we can update
14270 					 * cwnd.
14271 					 */
14272 					cwnd = tcp->tcp_cwnd + mss;
14273 					if (cwnd > tcp->tcp_cwnd_max)
14274 						cwnd = tcp->tcp_cwnd_max;
14275 					tcp->tcp_cwnd = cwnd;
14276 					if (tcp->tcp_unsent > 0)
14277 						flags |= TH_XMIT_NEEDED;
14278 					}
14279 				}
14280 			}
14281 		} else if (tcp->tcp_zero_win_probe) {
14282 			/*
14283 			 * If the window has opened, need to arrange
14284 			 * to send additional data.
14285 			 */
14286 			if (new_swnd != 0) {
14287 				/* tcp_suna != tcp_snxt */
14288 				/* Packet contains a window update */
14289 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14290 				tcp->tcp_zero_win_probe = 0;
14291 				tcp->tcp_timer_backoff = 0;
14292 				tcp->tcp_ms_we_have_waited = 0;
14293 
14294 				/*
14295 				 * Transmit starting with tcp_suna since
14296 				 * the one byte probe is not ack'ed.
14297 				 * If TCP has sent more than one identical
14298 				 * probe, tcp_rexmit will be set.  That means
14299 				 * tcp_ss_rexmit() will send out the one
14300 				 * byte along with new data.  Otherwise,
14301 				 * fake the retransmission.
14302 				 */
14303 				flags |= TH_XMIT_NEEDED;
14304 				if (!tcp->tcp_rexmit) {
14305 					tcp->tcp_rexmit = B_TRUE;
14306 					tcp->tcp_dupack_cnt = 0;
14307 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14308 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14309 				}
14310 			}
14311 		}
14312 		goto swnd_update;
14313 	}
14314 
14315 	/*
14316 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14317 	 * If the ACK value acks something that we have not yet sent, it might
14318 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14319 	 * other side.
14320 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14321 	 * state is handled above, so we can always just drop the segment and
14322 	 * send an ACK here.
14323 	 *
14324 	 * In the case where the peer shrinks the window, we see the new window
14325 	 * update, but all the data sent previously is queued up by the peer.
14326 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
14327 	 * number, which was already sent, and within window, is recorded.
14328 	 * tcp_snxt is then updated.
14329 	 *
14330 	 * If the window has previously shrunk, and an ACK for data not yet
14331 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
14332 	 * the ACK is for data within the window at the time the window was
14333 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
14334 	 * the sequence number ACK'ed.
14335 	 *
14336 	 * If the ACK covers all the data sent at the time the window was
14337 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
14338 	 *
14339 	 * Should we send ACKs in response to ACK only segments?
14340 	 */
14341 
14342 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14343 		if ((tcp->tcp_is_wnd_shrnk) &&
14344 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
14345 			uint32_t data_acked_ahead_snxt;
14346 
14347 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
14348 			tcp_update_xmit_tail(tcp, seg_ack);
14349 			tcp->tcp_unsent -= data_acked_ahead_snxt;
14350 		} else {
14351 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14352 			/* drop the received segment */
14353 			freemsg(mp);
14354 
14355 			/*
14356 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14357 			 * greater than 0, check if the number of such
14358 			 * bogus ACks is greater than that count.  If yes,
14359 			 * don't send back any ACK.  This prevents TCP from
14360 			 * getting into an ACK storm if somehow an attacker
14361 			 * successfully spoofs an acceptable segment to our
14362 			 * peer.
14363 			 */
14364 			if (tcp_drop_ack_unsent_cnt > 0 &&
14365 			    ++tcp->tcp_in_ack_unsent >
14366 			    tcp_drop_ack_unsent_cnt) {
14367 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14368 				return;
14369 			}
14370 			mp = tcp_ack_mp(tcp);
14371 			if (mp != NULL) {
14372 				BUMP_LOCAL(tcp->tcp_obsegs);
14373 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14374 				tcp_send_data(tcp, tcp->tcp_wq, mp);
14375 			}
14376 			return;
14377 		}
14378 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
14379 	    tcp->tcp_snxt_shrunk)) {
14380 			tcp->tcp_is_wnd_shrnk = B_FALSE;
14381 	}
14382 
14383 	/*
14384 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14385 	 * blocks that are covered by this ACK.
14386 	 */
14387 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14388 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14389 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14390 	}
14391 
14392 	/*
14393 	 * If we got an ACK after fast retransmit, check to see
14394 	 * if it is a partial ACK.  If it is not and the congestion
14395 	 * window was inflated to account for the other side's
14396 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14397 	 */
14398 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14399 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14400 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14401 			tcp->tcp_dupack_cnt = 0;
14402 			/*
14403 			 * Restore the orig tcp_cwnd_ssthresh after
14404 			 * fast retransmit phase.
14405 			 */
14406 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14407 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14408 			}
14409 			tcp->tcp_rexmit_max = seg_ack;
14410 			tcp->tcp_cwnd_cnt = 0;
14411 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14412 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14413 
14414 			/*
14415 			 * Remove all notsack info to avoid confusion with
14416 			 * the next fast retrasnmit/recovery phase.
14417 			 */
14418 			if (tcp->tcp_snd_sack_ok &&
14419 			    tcp->tcp_notsack_list != NULL) {
14420 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
14421 				    tcp);
14422 			}
14423 		} else {
14424 			if (tcp->tcp_snd_sack_ok &&
14425 			    tcp->tcp_notsack_list != NULL) {
14426 				flags |= TH_NEED_SACK_REXMIT;
14427 				tcp->tcp_pipe -= mss;
14428 				if (tcp->tcp_pipe < 0)
14429 					tcp->tcp_pipe = 0;
14430 			} else {
14431 				/*
14432 				 * Hoe's algorithm:
14433 				 *
14434 				 * Retransmit the unack'ed segment and
14435 				 * restart fast recovery.  Note that we
14436 				 * need to scale back tcp_cwnd to the
14437 				 * original value when we started fast
14438 				 * recovery.  This is to prevent overly
14439 				 * aggressive behaviour in sending new
14440 				 * segments.
14441 				 */
14442 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14443 				    tcps->tcps_dupack_fast_retransmit * mss;
14444 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14445 				flags |= TH_REXMIT_NEEDED;
14446 			}
14447 		}
14448 	} else {
14449 		tcp->tcp_dupack_cnt = 0;
14450 		if (tcp->tcp_rexmit) {
14451 			/*
14452 			 * TCP is retranmitting.  If the ACK ack's all
14453 			 * outstanding data, update tcp_rexmit_max and
14454 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14455 			 * to the correct value.
14456 			 *
14457 			 * Note that SEQ_LEQ() is used.  This is to avoid
14458 			 * unnecessary fast retransmit caused by dup ACKs
14459 			 * received when TCP does slow start retransmission
14460 			 * after a time out.  During this phase, TCP may
14461 			 * send out segments which are already received.
14462 			 * This causes dup ACKs to be sent back.
14463 			 */
14464 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14465 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14466 					tcp->tcp_rexmit_nxt = seg_ack;
14467 				}
14468 				if (seg_ack != tcp->tcp_rexmit_max) {
14469 					flags |= TH_XMIT_NEEDED;
14470 				}
14471 			} else {
14472 				tcp->tcp_rexmit = B_FALSE;
14473 				tcp->tcp_xmit_zc_clean = B_FALSE;
14474 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14475 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14476 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14477 			}
14478 			tcp->tcp_ms_we_have_waited = 0;
14479 		}
14480 	}
14481 
14482 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14483 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14484 	tcp->tcp_suna = seg_ack;
14485 	if (tcp->tcp_zero_win_probe != 0) {
14486 		tcp->tcp_zero_win_probe = 0;
14487 		tcp->tcp_timer_backoff = 0;
14488 	}
14489 
14490 	/*
14491 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14492 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14493 	 * will not reach here.
14494 	 */
14495 	if (mp1 == NULL) {
14496 		goto fin_acked;
14497 	}
14498 
14499 	/*
14500 	 * Update the congestion window.
14501 	 *
14502 	 * If TCP is not ECN capable or TCP is ECN capable but the
14503 	 * congestion experience bit is not set, increase the tcp_cwnd as
14504 	 * usual.
14505 	 */
14506 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14507 		cwnd = tcp->tcp_cwnd;
14508 		add = mss;
14509 
14510 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14511 			/*
14512 			 * This is to prevent an increase of less than 1 MSS of
14513 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14514 			 * may send out tinygrams in order to preserve mblk
14515 			 * boundaries.
14516 			 *
14517 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14518 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14519 			 * increased by 1 MSS for every RTTs.
14520 			 */
14521 			if (tcp->tcp_cwnd_cnt <= 0) {
14522 				tcp->tcp_cwnd_cnt = cwnd + add;
14523 			} else {
14524 				tcp->tcp_cwnd_cnt -= add;
14525 				add = 0;
14526 			}
14527 		}
14528 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14529 	}
14530 
14531 	/* See if the latest urgent data has been acknowledged */
14532 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14533 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14534 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14535 
14536 	/* Can we update the RTT estimates? */
14537 	if (tcp->tcp_snd_ts_ok) {
14538 		/* Ignore zero timestamp echo-reply. */
14539 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14540 			tcp_set_rto(tcp, (int32_t)lbolt -
14541 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14542 		}
14543 
14544 		/* If needed, restart the timer. */
14545 		if (tcp->tcp_set_timer == 1) {
14546 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14547 			tcp->tcp_set_timer = 0;
14548 		}
14549 		/*
14550 		 * Update tcp_csuna in case the other side stops sending
14551 		 * us timestamps.
14552 		 */
14553 		tcp->tcp_csuna = tcp->tcp_snxt;
14554 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14555 		/*
14556 		 * An ACK sequence we haven't seen before, so get the RTT
14557 		 * and update the RTO. But first check if the timestamp is
14558 		 * valid to use.
14559 		 */
14560 		if ((mp1->b_next != NULL) &&
14561 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14562 			tcp_set_rto(tcp, (int32_t)lbolt -
14563 			    (int32_t)(intptr_t)mp1->b_prev);
14564 		else
14565 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14566 
14567 		/* Remeber the last sequence to be ACKed */
14568 		tcp->tcp_csuna = seg_ack;
14569 		if (tcp->tcp_set_timer == 1) {
14570 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14571 			tcp->tcp_set_timer = 0;
14572 		}
14573 	} else {
14574 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14575 	}
14576 
14577 	/* Eat acknowledged bytes off the xmit queue. */
14578 	for (;;) {
14579 		mblk_t	*mp2;
14580 		uchar_t	*wptr;
14581 
14582 		wptr = mp1->b_wptr;
14583 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14584 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14585 		if (bytes_acked < 0) {
14586 			mp1->b_rptr = wptr + bytes_acked;
14587 			/*
14588 			 * Set a new timestamp if all the bytes timed by the
14589 			 * old timestamp have been ack'ed.
14590 			 */
14591 			if (SEQ_GT(seg_ack,
14592 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14593 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14594 				mp1->b_next = NULL;
14595 			}
14596 			break;
14597 		}
14598 		mp1->b_next = NULL;
14599 		mp1->b_prev = NULL;
14600 		mp2 = mp1;
14601 		mp1 = mp1->b_cont;
14602 
14603 		/*
14604 		 * This notification is required for some zero-copy
14605 		 * clients to maintain a copy semantic. After the data
14606 		 * is ack'ed, client is safe to modify or reuse the buffer.
14607 		 */
14608 		if (tcp->tcp_snd_zcopy_aware &&
14609 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14610 			tcp_zcopy_notify(tcp);
14611 		freeb(mp2);
14612 		if (bytes_acked == 0) {
14613 			if (mp1 == NULL) {
14614 				/* Everything is ack'ed, clear the tail. */
14615 				tcp->tcp_xmit_tail = NULL;
14616 				/*
14617 				 * Cancel the timer unless we are still
14618 				 * waiting for an ACK for the FIN packet.
14619 				 */
14620 				if (tcp->tcp_timer_tid != 0 &&
14621 				    tcp->tcp_snxt == tcp->tcp_suna) {
14622 					(void) TCP_TIMER_CANCEL(tcp,
14623 					    tcp->tcp_timer_tid);
14624 					tcp->tcp_timer_tid = 0;
14625 				}
14626 				goto pre_swnd_update;
14627 			}
14628 			if (mp2 != tcp->tcp_xmit_tail)
14629 				break;
14630 			tcp->tcp_xmit_tail = mp1;
14631 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14632 			    (uintptr_t)INT_MAX);
14633 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14634 			    mp1->b_rptr);
14635 			break;
14636 		}
14637 		if (mp1 == NULL) {
14638 			/*
14639 			 * More was acked but there is nothing more
14640 			 * outstanding.  This means that the FIN was
14641 			 * just acked or that we're talking to a clown.
14642 			 */
14643 fin_acked:
14644 			ASSERT(tcp->tcp_fin_sent);
14645 			tcp->tcp_xmit_tail = NULL;
14646 			if (tcp->tcp_fin_sent) {
14647 				/* FIN was acked - making progress */
14648 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14649 				    !tcp->tcp_fin_acked)
14650 					tcp->tcp_ip_forward_progress = B_TRUE;
14651 				tcp->tcp_fin_acked = B_TRUE;
14652 				if (tcp->tcp_linger_tid != 0 &&
14653 				    TCP_TIMER_CANCEL(tcp,
14654 				    tcp->tcp_linger_tid) >= 0) {
14655 					tcp_stop_lingering(tcp);
14656 					freemsg(mp);
14657 					mp = NULL;
14658 				}
14659 			} else {
14660 				/*
14661 				 * We should never get here because
14662 				 * we have already checked that the
14663 				 * number of bytes ack'ed should be
14664 				 * smaller than or equal to what we
14665 				 * have sent so far (it is the
14666 				 * acceptability check of the ACK).
14667 				 * We can only get here if the send
14668 				 * queue is corrupted.
14669 				 *
14670 				 * Terminate the connection and
14671 				 * panic the system.  It is better
14672 				 * for us to panic instead of
14673 				 * continuing to avoid other disaster.
14674 				 */
14675 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14676 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14677 				panic("Memory corruption "
14678 				    "detected for connection %s.",
14679 				    tcp_display(tcp, NULL,
14680 				    DISP_ADDR_AND_PORT));
14681 				/*NOTREACHED*/
14682 			}
14683 			goto pre_swnd_update;
14684 		}
14685 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14686 	}
14687 	if (tcp->tcp_unsent) {
14688 		flags |= TH_XMIT_NEEDED;
14689 	}
14690 pre_swnd_update:
14691 	tcp->tcp_xmit_head = mp1;
14692 swnd_update:
14693 	/*
14694 	 * The following check is different from most other implementations.
14695 	 * For bi-directional transfer, when segments are dropped, the
14696 	 * "normal" check will not accept a window update in those
14697 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14698 	 * segments which are outside receiver's window.  As TCP accepts
14699 	 * the ack in those retransmitted segments, if the window update in
14700 	 * the same segment is not accepted, TCP will incorrectly calculates
14701 	 * that it can send more segments.  This can create a deadlock
14702 	 * with the receiver if its window becomes zero.
14703 	 */
14704 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14705 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14706 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14707 		/*
14708 		 * The criteria for update is:
14709 		 *
14710 		 * 1. the segment acknowledges some data.  Or
14711 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14712 		 * 3. the segment is not old and the advertised window is
14713 		 * larger than the previous advertised window.
14714 		 */
14715 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14716 			flags |= TH_XMIT_NEEDED;
14717 		tcp->tcp_swnd = new_swnd;
14718 		if (new_swnd > tcp->tcp_max_swnd)
14719 			tcp->tcp_max_swnd = new_swnd;
14720 		tcp->tcp_swl1 = seg_seq;
14721 		tcp->tcp_swl2 = seg_ack;
14722 	}
14723 est:
14724 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14725 
14726 		switch (tcp->tcp_state) {
14727 		case TCPS_FIN_WAIT_1:
14728 			if (tcp->tcp_fin_acked) {
14729 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14730 				/*
14731 				 * We implement the non-standard BSD/SunOS
14732 				 * FIN_WAIT_2 flushing algorithm.
14733 				 * If there is no user attached to this
14734 				 * TCP endpoint, then this TCP struct
14735 				 * could hang around forever in FIN_WAIT_2
14736 				 * state if the peer forgets to send us
14737 				 * a FIN.  To prevent this, we wait only
14738 				 * 2*MSL (a convenient time value) for
14739 				 * the FIN to arrive.  If it doesn't show up,
14740 				 * we flush the TCP endpoint.  This algorithm,
14741 				 * though a violation of RFC-793, has worked
14742 				 * for over 10 years in BSD systems.
14743 				 * Note: SunOS 4.x waits 675 seconds before
14744 				 * flushing the FIN_WAIT_2 connection.
14745 				 */
14746 				TCP_TIMER_RESTART(tcp,
14747 				    tcps->tcps_fin_wait_2_flush_interval);
14748 			}
14749 			break;
14750 		case TCPS_FIN_WAIT_2:
14751 			break;	/* Shutdown hook? */
14752 		case TCPS_LAST_ACK:
14753 			freemsg(mp);
14754 			if (tcp->tcp_fin_acked) {
14755 				(void) tcp_clean_death(tcp, 0, 19);
14756 				return;
14757 			}
14758 			goto xmit_check;
14759 		case TCPS_CLOSING:
14760 			if (tcp->tcp_fin_acked) {
14761 				tcp->tcp_state = TCPS_TIME_WAIT;
14762 				/*
14763 				 * Unconditionally clear the exclusive binding
14764 				 * bit so this TIME-WAIT connection won't
14765 				 * interfere with new ones.
14766 				 */
14767 				tcp->tcp_exclbind = 0;
14768 				if (!TCP_IS_DETACHED(tcp)) {
14769 					TCP_TIMER_RESTART(tcp,
14770 					    tcps->tcps_time_wait_interval);
14771 				} else {
14772 					tcp_time_wait_append(tcp);
14773 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14774 				}
14775 			}
14776 			/*FALLTHRU*/
14777 		case TCPS_CLOSE_WAIT:
14778 			freemsg(mp);
14779 			goto xmit_check;
14780 		default:
14781 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14782 			break;
14783 		}
14784 	}
14785 	if (flags & TH_FIN) {
14786 		/* Make sure we ack the fin */
14787 		flags |= TH_ACK_NEEDED;
14788 		if (!tcp->tcp_fin_rcvd) {
14789 			tcp->tcp_fin_rcvd = B_TRUE;
14790 			tcp->tcp_rnxt++;
14791 			tcph = tcp->tcp_tcph;
14792 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14793 
14794 			/*
14795 			 * Generate the ordrel_ind at the end unless we
14796 			 * are an eager guy.
14797 			 * In the eager case tcp_rsrv will do this when run
14798 			 * after tcp_accept is done.
14799 			 */
14800 			if (tcp->tcp_listener == NULL &&
14801 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14802 				flags |= TH_ORDREL_NEEDED;
14803 			switch (tcp->tcp_state) {
14804 			case TCPS_SYN_RCVD:
14805 			case TCPS_ESTABLISHED:
14806 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14807 				/* Keepalive? */
14808 				break;
14809 			case TCPS_FIN_WAIT_1:
14810 				if (!tcp->tcp_fin_acked) {
14811 					tcp->tcp_state = TCPS_CLOSING;
14812 					break;
14813 				}
14814 				/* FALLTHRU */
14815 			case TCPS_FIN_WAIT_2:
14816 				tcp->tcp_state = TCPS_TIME_WAIT;
14817 				/*
14818 				 * Unconditionally clear the exclusive binding
14819 				 * bit so this TIME-WAIT connection won't
14820 				 * interfere with new ones.
14821 				 */
14822 				tcp->tcp_exclbind = 0;
14823 				if (!TCP_IS_DETACHED(tcp)) {
14824 					TCP_TIMER_RESTART(tcp,
14825 					    tcps->tcps_time_wait_interval);
14826 				} else {
14827 					tcp_time_wait_append(tcp);
14828 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14829 				}
14830 				if (seg_len) {
14831 					/*
14832 					 * implies data piggybacked on FIN.
14833 					 * break to handle data.
14834 					 */
14835 					break;
14836 				}
14837 				freemsg(mp);
14838 				goto ack_check;
14839 			}
14840 		}
14841 	}
14842 	if (mp == NULL)
14843 		goto xmit_check;
14844 	if (seg_len == 0) {
14845 		freemsg(mp);
14846 		goto xmit_check;
14847 	}
14848 	if (mp->b_rptr == mp->b_wptr) {
14849 		/*
14850 		 * The header has been consumed, so we remove the
14851 		 * zero-length mblk here.
14852 		 */
14853 		mp1 = mp;
14854 		mp = mp->b_cont;
14855 		freeb(mp1);
14856 	}
14857 update_ack:
14858 	tcph = tcp->tcp_tcph;
14859 	tcp->tcp_rack_cnt++;
14860 	{
14861 		uint32_t cur_max;
14862 
14863 		cur_max = tcp->tcp_rack_cur_max;
14864 		if (tcp->tcp_rack_cnt >= cur_max) {
14865 			/*
14866 			 * We have more unacked data than we should - send
14867 			 * an ACK now.
14868 			 */
14869 			flags |= TH_ACK_NEEDED;
14870 			cur_max++;
14871 			if (cur_max > tcp->tcp_rack_abs_max)
14872 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14873 			else
14874 				tcp->tcp_rack_cur_max = cur_max;
14875 		} else if (TCP_IS_DETACHED(tcp)) {
14876 			/* We don't have an ACK timer for detached TCP. */
14877 			flags |= TH_ACK_NEEDED;
14878 		} else if (seg_len < mss) {
14879 			/*
14880 			 * If we get a segment that is less than an mss, and we
14881 			 * already have unacknowledged data, and the amount
14882 			 * unacknowledged is not a multiple of mss, then we
14883 			 * better generate an ACK now.  Otherwise, this may be
14884 			 * the tail piece of a transaction, and we would rather
14885 			 * wait for the response.
14886 			 */
14887 			uint32_t udif;
14888 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14889 			    (uintptr_t)INT_MAX);
14890 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14891 			if (udif && (udif % mss))
14892 				flags |= TH_ACK_NEEDED;
14893 			else
14894 				flags |= TH_ACK_TIMER_NEEDED;
14895 		} else {
14896 			/* Start delayed ack timer */
14897 			flags |= TH_ACK_TIMER_NEEDED;
14898 		}
14899 	}
14900 	tcp->tcp_rnxt += seg_len;
14901 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14902 
14903 	if (mp == NULL)
14904 		goto xmit_check;
14905 
14906 	/* Update SACK list */
14907 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14908 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14909 		    &(tcp->tcp_num_sack_blk));
14910 	}
14911 
14912 	if (tcp->tcp_urp_mp) {
14913 		tcp->tcp_urp_mp->b_cont = mp;
14914 		mp = tcp->tcp_urp_mp;
14915 		tcp->tcp_urp_mp = NULL;
14916 		/* Ready for a new signal. */
14917 		tcp->tcp_urp_last_valid = B_FALSE;
14918 #ifdef DEBUG
14919 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14920 		    "tcp_rput: sending exdata_ind %s",
14921 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14922 #endif /* DEBUG */
14923 	}
14924 
14925 	/*
14926 	 * Check for ancillary data changes compared to last segment.
14927 	 */
14928 	if (tcp->tcp_ipv6_recvancillary != 0) {
14929 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14930 		ASSERT(mp != NULL);
14931 	}
14932 
14933 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14934 		/*
14935 		 * Side queue inbound data until the accept happens.
14936 		 * tcp_accept/tcp_rput drains this when the accept happens.
14937 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14938 		 * T_EXDATA_IND) it is queued on b_next.
14939 		 * XXX Make urgent data use this. Requires:
14940 		 *	Removing tcp_listener check for TH_URG
14941 		 *	Making M_PCPROTO and MARK messages skip the eager case
14942 		 */
14943 
14944 		if (tcp->tcp_kssl_pending) {
14945 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
14946 			    mblk_t *, mp);
14947 			tcp_kssl_input(tcp, mp);
14948 		} else {
14949 			tcp_rcv_enqueue(tcp, mp, seg_len);
14950 		}
14951 	} else if (IPCL_IS_NONSTR(connp)) {
14952 		/*
14953 		 * Non-STREAMS socket
14954 		 *
14955 		 * Note that no KSSL processing is done here, because
14956 		 * KSSL is not supported for non-STREAMS sockets.
14957 		 */
14958 		boolean_t push = flags & (TH_PUSH|TH_FIN);
14959 		int error;
14960 
14961 		if ((*connp->conn_upcalls->su_recv)(
14962 		    connp->conn_upper_handle,
14963 		    mp, seg_len, 0, &error, &push) <= 0) {
14964 			/*
14965 			 * We should never be in middle of a
14966 			 * fallback, the squeue guarantees that.
14967 			 */
14968 			ASSERT(error != EOPNOTSUPP);
14969 			if (error == ENOSPC)
14970 				tcp->tcp_rwnd -= seg_len;
14971 		} else if (push) {
14972 			/* PUSH bit set and sockfs is not flow controlled */
14973 			flags |= tcp_rwnd_reopen(tcp);
14974 		}
14975 	} else {
14976 		/* STREAMS socket */
14977 		if (mp->b_datap->db_type != M_DATA ||
14978 		    (flags & TH_MARKNEXT_NEEDED)) {
14979 			if (tcp->tcp_rcv_list != NULL) {
14980 				flags |= tcp_rcv_drain(tcp);
14981 			}
14982 			ASSERT(tcp->tcp_rcv_list == NULL ||
14983 			    tcp->tcp_fused_sigurg);
14984 
14985 			if (flags & TH_MARKNEXT_NEEDED) {
14986 #ifdef DEBUG
14987 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14988 				    "tcp_rput: sending MSGMARKNEXT %s",
14989 				    tcp_display(tcp, NULL,
14990 				    DISP_PORT_ONLY));
14991 #endif /* DEBUG */
14992 				mp->b_flag |= MSGMARKNEXT;
14993 				flags &= ~TH_MARKNEXT_NEEDED;
14994 			}
14995 
14996 			/* Does this need SSL processing first? */
14997 			if ((tcp->tcp_kssl_ctx != NULL) &&
14998 			    (DB_TYPE(mp) == M_DATA)) {
14999 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15000 				    mblk_t *, mp);
15001 				tcp_kssl_input(tcp, mp);
15002 			} else {
15003 				putnext(tcp->tcp_rq, mp);
15004 				if (!canputnext(tcp->tcp_rq))
15005 					tcp->tcp_rwnd -= seg_len;
15006 			}
15007 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15008 		    (DB_TYPE(mp) == M_DATA)) {
15009 			/* Does this need SSL processing first? */
15010 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15011 			tcp_kssl_input(tcp, mp);
15012 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15013 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15014 			if (tcp->tcp_rcv_list != NULL) {
15015 				/*
15016 				 * Enqueue the new segment first and then
15017 				 * call tcp_rcv_drain() to send all data
15018 				 * up.  The other way to do this is to
15019 				 * send all queued data up and then call
15020 				 * putnext() to send the new segment up.
15021 				 * This way can remove the else part later
15022 				 * on.
15023 				 *
15024 				 * We don't do this to avoid one more call to
15025 				 * canputnext() as tcp_rcv_drain() needs to
15026 				 * call canputnext().
15027 				 */
15028 				tcp_rcv_enqueue(tcp, mp, seg_len);
15029 				flags |= tcp_rcv_drain(tcp);
15030 			} else {
15031 				putnext(tcp->tcp_rq, mp);
15032 				if (!canputnext(tcp->tcp_rq))
15033 					tcp->tcp_rwnd -= seg_len;
15034 			}
15035 		} else {
15036 			/*
15037 			 * Enqueue all packets when processing an mblk
15038 			 * from the co queue and also enqueue normal packets.
15039 			 */
15040 			tcp_rcv_enqueue(tcp, mp, seg_len);
15041 		}
15042 		/*
15043 		 * Make sure the timer is running if we have data waiting
15044 		 * for a push bit. This provides resiliency against
15045 		 * implementations that do not correctly generate push bits.
15046 		 */
15047 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
15048 			/*
15049 			 * The connection may be closed at this point, so don't
15050 			 * do anything for a detached tcp.
15051 			 */
15052 			if (!TCP_IS_DETACHED(tcp))
15053 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15054 				    tcp_push_timer,
15055 				    MSEC_TO_TICK(
15056 				    tcps->tcps_push_timer_interval));
15057 		}
15058 	}
15059 
15060 xmit_check:
15061 	/* Is there anything left to do? */
15062 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15063 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15064 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15065 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15066 		goto done;
15067 
15068 	/* Any transmit work to do and a non-zero window? */
15069 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15070 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15071 		if (flags & TH_REXMIT_NEEDED) {
15072 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15073 
15074 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15075 			if (snd_size > mss)
15076 				snd_size = mss;
15077 			if (snd_size > tcp->tcp_swnd)
15078 				snd_size = tcp->tcp_swnd;
15079 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15080 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15081 			    B_TRUE);
15082 
15083 			if (mp1 != NULL) {
15084 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15085 				tcp->tcp_csuna = tcp->tcp_snxt;
15086 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15087 				UPDATE_MIB(&tcps->tcps_mib,
15088 				    tcpRetransBytes, snd_size);
15089 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15090 			}
15091 		}
15092 		if (flags & TH_NEED_SACK_REXMIT) {
15093 			tcp_sack_rxmit(tcp, &flags);
15094 		}
15095 		/*
15096 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15097 		 * out new segment.  Note that tcp_rexmit should not be
15098 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15099 		 */
15100 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15101 			if (!tcp->tcp_rexmit) {
15102 				tcp_wput_data(tcp, NULL, B_FALSE);
15103 			} else {
15104 				tcp_ss_rexmit(tcp);
15105 			}
15106 		}
15107 		/*
15108 		 * Adjust tcp_cwnd back to normal value after sending
15109 		 * new data segments.
15110 		 */
15111 		if (flags & TH_LIMIT_XMIT) {
15112 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15113 			/*
15114 			 * This will restart the timer.  Restarting the
15115 			 * timer is used to avoid a timeout before the
15116 			 * limited transmitted segment's ACK gets back.
15117 			 */
15118 			if (tcp->tcp_xmit_head != NULL)
15119 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15120 		}
15121 
15122 		/* Anything more to do? */
15123 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15124 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15125 			goto done;
15126 	}
15127 ack_check:
15128 	if (flags & TH_SEND_URP_MARK) {
15129 		ASSERT(tcp->tcp_urp_mark_mp);
15130 		ASSERT(!IPCL_IS_NONSTR(connp));
15131 		/*
15132 		 * Send up any queued data and then send the mark message
15133 		 */
15134 		if (tcp->tcp_rcv_list != NULL) {
15135 			flags |= tcp_rcv_drain(tcp);
15136 
15137 		}
15138 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15139 		mp1 = tcp->tcp_urp_mark_mp;
15140 		tcp->tcp_urp_mark_mp = NULL;
15141 		putnext(tcp->tcp_rq, mp1);
15142 #ifdef DEBUG
15143 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15144 		    "tcp_rput: sending zero-length %s %s",
15145 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15146 		    "MSGNOTMARKNEXT"),
15147 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15148 #endif /* DEBUG */
15149 		flags &= ~TH_SEND_URP_MARK;
15150 	}
15151 	if (flags & TH_ACK_NEEDED) {
15152 		/*
15153 		 * Time to send an ack for some reason.
15154 		 */
15155 		mp1 = tcp_ack_mp(tcp);
15156 
15157 		if (mp1 != NULL) {
15158 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15159 			BUMP_LOCAL(tcp->tcp_obsegs);
15160 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15161 		}
15162 		if (tcp->tcp_ack_tid != 0) {
15163 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15164 			tcp->tcp_ack_tid = 0;
15165 		}
15166 	}
15167 	if (flags & TH_ACK_TIMER_NEEDED) {
15168 		/*
15169 		 * Arrange for deferred ACK or push wait timeout.
15170 		 * Start timer if it is not already running.
15171 		 */
15172 		if (tcp->tcp_ack_tid == 0) {
15173 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15174 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15175 			    (clock_t)tcps->tcps_local_dack_interval :
15176 			    (clock_t)tcps->tcps_deferred_ack_interval));
15177 		}
15178 	}
15179 	if (flags & TH_ORDREL_NEEDED) {
15180 		/*
15181 		 * Send up the ordrel_ind unless we are an eager guy.
15182 		 * In the eager case tcp_rsrv will do this when run
15183 		 * after tcp_accept is done.
15184 		 */
15185 		ASSERT(tcp->tcp_listener == NULL);
15186 
15187 		if (IPCL_IS_NONSTR(connp)) {
15188 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15189 			tcp->tcp_ordrel_done = B_TRUE;
15190 			(*connp->conn_upcalls->su_opctl)
15191 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15192 			goto done;
15193 		}
15194 
15195 		if (tcp->tcp_rcv_list != NULL) {
15196 			/*
15197 			 * Push any mblk(s) enqueued from co processing.
15198 			 */
15199 			flags |= tcp_rcv_drain(tcp);
15200 		}
15201 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15202 
15203 		mp1 = tcp->tcp_ordrel_mp;
15204 		tcp->tcp_ordrel_mp = NULL;
15205 		tcp->tcp_ordrel_done = B_TRUE;
15206 		putnext(tcp->tcp_rq, mp1);
15207 	}
15208 done:
15209 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15210 }
15211 
15212 /*
15213  * This routine adjusts next-to-send sequence number variables, in the
15214  * case where the reciever has shrunk it's window.
15215  */
15216 static void
15217 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
15218 {
15219 	mblk_t *xmit_tail;
15220 	int32_t offset;
15221 
15222 	tcp->tcp_snxt = snxt;
15223 
15224 	/* Get the mblk, and the offset in it, as per the shrunk window */
15225 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
15226 	ASSERT(xmit_tail != NULL);
15227 	tcp->tcp_xmit_tail = xmit_tail;
15228 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
15229 	    xmit_tail->b_rptr - offset;
15230 }
15231 
15232 /*
15233  * This function does PAWS protection check. Returns B_TRUE if the
15234  * segment passes the PAWS test, else returns B_FALSE.
15235  */
15236 boolean_t
15237 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15238 {
15239 	uint8_t	flags;
15240 	int	options;
15241 	uint8_t *up;
15242 
15243 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15244 	/*
15245 	 * If timestamp option is aligned nicely, get values inline,
15246 	 * otherwise call general routine to parse.  Only do that
15247 	 * if timestamp is the only option.
15248 	 */
15249 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15250 	    TCPOPT_REAL_TS_LEN &&
15251 	    OK_32PTR((up = ((uint8_t *)tcph) +
15252 	    TCP_MIN_HEADER_LENGTH)) &&
15253 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15254 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15255 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15256 
15257 		options = TCP_OPT_TSTAMP_PRESENT;
15258 	} else {
15259 		if (tcp->tcp_snd_sack_ok) {
15260 			tcpoptp->tcp = tcp;
15261 		} else {
15262 			tcpoptp->tcp = NULL;
15263 		}
15264 		options = tcp_parse_options(tcph, tcpoptp);
15265 	}
15266 
15267 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15268 		/*
15269 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15270 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15271 		 */
15272 		if ((flags & TH_RST) == 0 &&
15273 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15274 		    tcp->tcp_ts_recent)) {
15275 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15276 			    PAWS_TIMEOUT)) {
15277 				/* This segment is not acceptable. */
15278 				return (B_FALSE);
15279 			} else {
15280 				/*
15281 				 * Connection has been idle for
15282 				 * too long.  Reset the timestamp
15283 				 * and assume the segment is valid.
15284 				 */
15285 				tcp->tcp_ts_recent =
15286 				    tcpoptp->tcp_opt_ts_val;
15287 			}
15288 		}
15289 	} else {
15290 		/*
15291 		 * If we don't get a timestamp on every packet, we
15292 		 * figure we can't really trust 'em, so we stop sending
15293 		 * and parsing them.
15294 		 */
15295 		tcp->tcp_snd_ts_ok = B_FALSE;
15296 
15297 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15298 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15299 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15300 		/*
15301 		 * Adjust the tcp_mss accordingly. We also need to
15302 		 * adjust tcp_cwnd here in accordance with the new mss.
15303 		 * But we avoid doing a slow start here so as to not
15304 		 * to lose on the transfer rate built up so far.
15305 		 */
15306 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15307 		if (tcp->tcp_snd_sack_ok) {
15308 			ASSERT(tcp->tcp_sack_info != NULL);
15309 			tcp->tcp_max_sack_blk = 4;
15310 		}
15311 	}
15312 	return (B_TRUE);
15313 }
15314 
15315 /*
15316  * Attach ancillary data to a received TCP segments for the
15317  * ancillary pieces requested by the application that are
15318  * different than they were in the previous data segment.
15319  *
15320  * Save the "current" values once memory allocation is ok so that
15321  * when memory allocation fails we can just wait for the next data segment.
15322  */
15323 static mblk_t *
15324 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15325 {
15326 	struct T_optdata_ind *todi;
15327 	int optlen;
15328 	uchar_t *optptr;
15329 	struct T_opthdr *toh;
15330 	uint_t addflag;	/* Which pieces to add */
15331 	mblk_t *mp1;
15332 
15333 	optlen = 0;
15334 	addflag = 0;
15335 	/* If app asked for pktinfo and the index has changed ... */
15336 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15337 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15338 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15339 		optlen += sizeof (struct T_opthdr) +
15340 		    sizeof (struct in6_pktinfo);
15341 		addflag |= TCP_IPV6_RECVPKTINFO;
15342 	}
15343 	/* If app asked for hoplimit and it has changed ... */
15344 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15345 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15346 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15347 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15348 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15349 	}
15350 	/* If app asked for tclass and it has changed ... */
15351 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15352 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15353 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15354 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15355 		addflag |= TCP_IPV6_RECVTCLASS;
15356 	}
15357 	/*
15358 	 * If app asked for hopbyhop headers and it has changed ...
15359 	 * For security labels, note that (1) security labels can't change on
15360 	 * a connected socket at all, (2) we're connected to at most one peer,
15361 	 * (3) if anything changes, then it must be some other extra option.
15362 	 */
15363 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15364 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15365 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15366 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15367 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15368 		    tcp->tcp_label_len;
15369 		addflag |= TCP_IPV6_RECVHOPOPTS;
15370 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15371 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15372 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15373 			return (mp);
15374 	}
15375 	/* If app asked for dst headers before routing headers ... */
15376 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15377 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15378 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15379 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15380 		optlen += sizeof (struct T_opthdr) +
15381 		    ipp->ipp_rtdstoptslen;
15382 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15383 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15384 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15385 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15386 			return (mp);
15387 	}
15388 	/* If app asked for routing headers and it has changed ... */
15389 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15390 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15391 	    (ipp->ipp_fields & IPPF_RTHDR),
15392 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15393 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15394 		addflag |= TCP_IPV6_RECVRTHDR;
15395 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15396 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15397 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15398 			return (mp);
15399 	}
15400 	/* If app asked for dest headers and it has changed ... */
15401 	if ((tcp->tcp_ipv6_recvancillary &
15402 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15403 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15404 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15405 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15406 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15407 		addflag |= TCP_IPV6_RECVDSTOPTS;
15408 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15409 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15410 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15411 			return (mp);
15412 	}
15413 
15414 	if (optlen == 0) {
15415 		/* Nothing to add */
15416 		return (mp);
15417 	}
15418 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15419 	if (mp1 == NULL) {
15420 		/*
15421 		 * Defer sending ancillary data until the next TCP segment
15422 		 * arrives.
15423 		 */
15424 		return (mp);
15425 	}
15426 	mp1->b_cont = mp;
15427 	mp = mp1;
15428 	mp->b_wptr += sizeof (*todi) + optlen;
15429 	mp->b_datap->db_type = M_PROTO;
15430 	todi = (struct T_optdata_ind *)mp->b_rptr;
15431 	todi->PRIM_type = T_OPTDATA_IND;
15432 	todi->DATA_flag = 1;	/* MORE data */
15433 	todi->OPT_length = optlen;
15434 	todi->OPT_offset = sizeof (*todi);
15435 	optptr = (uchar_t *)&todi[1];
15436 	/*
15437 	 * If app asked for pktinfo and the index has changed ...
15438 	 * Note that the local address never changes for the connection.
15439 	 */
15440 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15441 		struct in6_pktinfo *pkti;
15442 
15443 		toh = (struct T_opthdr *)optptr;
15444 		toh->level = IPPROTO_IPV6;
15445 		toh->name = IPV6_PKTINFO;
15446 		toh->len = sizeof (*toh) + sizeof (*pkti);
15447 		toh->status = 0;
15448 		optptr += sizeof (*toh);
15449 		pkti = (struct in6_pktinfo *)optptr;
15450 		if (tcp->tcp_ipversion == IPV6_VERSION)
15451 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15452 		else
15453 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15454 			    &pkti->ipi6_addr);
15455 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15456 		optptr += sizeof (*pkti);
15457 		ASSERT(OK_32PTR(optptr));
15458 		/* Save as "last" value */
15459 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15460 	}
15461 	/* If app asked for hoplimit and it has changed ... */
15462 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15463 		toh = (struct T_opthdr *)optptr;
15464 		toh->level = IPPROTO_IPV6;
15465 		toh->name = IPV6_HOPLIMIT;
15466 		toh->len = sizeof (*toh) + sizeof (uint_t);
15467 		toh->status = 0;
15468 		optptr += sizeof (*toh);
15469 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15470 		optptr += sizeof (uint_t);
15471 		ASSERT(OK_32PTR(optptr));
15472 		/* Save as "last" value */
15473 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15474 	}
15475 	/* If app asked for tclass and it has changed ... */
15476 	if (addflag & TCP_IPV6_RECVTCLASS) {
15477 		toh = (struct T_opthdr *)optptr;
15478 		toh->level = IPPROTO_IPV6;
15479 		toh->name = IPV6_TCLASS;
15480 		toh->len = sizeof (*toh) + sizeof (uint_t);
15481 		toh->status = 0;
15482 		optptr += sizeof (*toh);
15483 		*(uint_t *)optptr = ipp->ipp_tclass;
15484 		optptr += sizeof (uint_t);
15485 		ASSERT(OK_32PTR(optptr));
15486 		/* Save as "last" value */
15487 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15488 	}
15489 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15490 		toh = (struct T_opthdr *)optptr;
15491 		toh->level = IPPROTO_IPV6;
15492 		toh->name = IPV6_HOPOPTS;
15493 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15494 		    tcp->tcp_label_len;
15495 		toh->status = 0;
15496 		optptr += sizeof (*toh);
15497 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15498 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15499 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15500 		ASSERT(OK_32PTR(optptr));
15501 		/* Save as last value */
15502 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15503 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15504 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15505 	}
15506 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15507 		toh = (struct T_opthdr *)optptr;
15508 		toh->level = IPPROTO_IPV6;
15509 		toh->name = IPV6_RTHDRDSTOPTS;
15510 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15511 		toh->status = 0;
15512 		optptr += sizeof (*toh);
15513 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15514 		optptr += ipp->ipp_rtdstoptslen;
15515 		ASSERT(OK_32PTR(optptr));
15516 		/* Save as last value */
15517 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15518 		    &tcp->tcp_rtdstoptslen,
15519 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15520 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15521 	}
15522 	if (addflag & TCP_IPV6_RECVRTHDR) {
15523 		toh = (struct T_opthdr *)optptr;
15524 		toh->level = IPPROTO_IPV6;
15525 		toh->name = IPV6_RTHDR;
15526 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15527 		toh->status = 0;
15528 		optptr += sizeof (*toh);
15529 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15530 		optptr += ipp->ipp_rthdrlen;
15531 		ASSERT(OK_32PTR(optptr));
15532 		/* Save as last value */
15533 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15534 		    (ipp->ipp_fields & IPPF_RTHDR),
15535 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15536 	}
15537 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15538 		toh = (struct T_opthdr *)optptr;
15539 		toh->level = IPPROTO_IPV6;
15540 		toh->name = IPV6_DSTOPTS;
15541 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15542 		toh->status = 0;
15543 		optptr += sizeof (*toh);
15544 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15545 		optptr += ipp->ipp_dstoptslen;
15546 		ASSERT(OK_32PTR(optptr));
15547 		/* Save as last value */
15548 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15549 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15550 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15551 	}
15552 	ASSERT(optptr == mp->b_wptr);
15553 	return (mp);
15554 }
15555 
15556 /*
15557  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15558  * messages.
15559  */
15560 void
15561 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15562 {
15563 	uchar_t	*rptr = mp->b_rptr;
15564 	queue_t	*q = tcp->tcp_rq;
15565 	struct T_error_ack *tea;
15566 
15567 	switch (mp->b_datap->db_type) {
15568 	case M_PROTO:
15569 	case M_PCPROTO:
15570 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15571 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15572 			break;
15573 		tea = (struct T_error_ack *)rptr;
15574 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15575 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15576 		    tea->ERROR_prim != T_BIND_REQ);
15577 		switch (tea->PRIM_type) {
15578 		case T_ERROR_ACK:
15579 			if (tcp->tcp_debug) {
15580 				(void) strlog(TCP_MOD_ID, 0, 1,
15581 				    SL_TRACE|SL_ERROR,
15582 				    "tcp_rput_other: case T_ERROR_ACK, "
15583 				    "ERROR_prim == %d",
15584 				    tea->ERROR_prim);
15585 			}
15586 			switch (tea->ERROR_prim) {
15587 			case T_SVR4_OPTMGMT_REQ:
15588 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15589 					/* T_OPTMGMT_REQ generated by TCP */
15590 					printf("T_SVR4_OPTMGMT_REQ failed "
15591 					    "%d/%d - dropped (cnt %d)\n",
15592 					    tea->TLI_error, tea->UNIX_error,
15593 					    tcp->tcp_drop_opt_ack_cnt);
15594 					freemsg(mp);
15595 					tcp->tcp_drop_opt_ack_cnt--;
15596 					return;
15597 				}
15598 				break;
15599 			}
15600 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15601 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15602 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15603 				    "- dropped (cnt %d)\n",
15604 				    tea->TLI_error, tea->UNIX_error,
15605 				    tcp->tcp_drop_opt_ack_cnt);
15606 				freemsg(mp);
15607 				tcp->tcp_drop_opt_ack_cnt--;
15608 				return;
15609 			}
15610 			break;
15611 		case T_OPTMGMT_ACK:
15612 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15613 				/* T_OPTMGMT_REQ generated by TCP */
15614 				freemsg(mp);
15615 				tcp->tcp_drop_opt_ack_cnt--;
15616 				return;
15617 			}
15618 			break;
15619 		default:
15620 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15621 			break;
15622 		}
15623 		break;
15624 	case M_FLUSH:
15625 		if (*rptr & FLUSHR)
15626 			flushq(q, FLUSHDATA);
15627 		break;
15628 	default:
15629 		/* M_CTL will be directly sent to tcp_icmp_error() */
15630 		ASSERT(DB_TYPE(mp) != M_CTL);
15631 		break;
15632 	}
15633 	/*
15634 	 * Make sure we set this bit before sending the ACK for
15635 	 * bind. Otherwise accept could possibly run and free
15636 	 * this tcp struct.
15637 	 */
15638 	ASSERT(q != NULL);
15639 	putnext(q, mp);
15640 }
15641 
15642 /* ARGSUSED */
15643 static void
15644 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15645 {
15646 	conn_t	*connp = (conn_t *)arg;
15647 	tcp_t	*tcp = connp->conn_tcp;
15648 	queue_t	*q = tcp->tcp_rq;
15649 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15650 
15651 	ASSERT(!IPCL_IS_NONSTR(connp));
15652 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15653 	tcp->tcp_rsrv_mp = mp;
15654 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15655 
15656 	TCP_STAT(tcps, tcp_rsrv_calls);
15657 
15658 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15659 		return;
15660 	}
15661 
15662 	if (tcp->tcp_fused) {
15663 		tcp_fuse_backenable(tcp);
15664 		return;
15665 	}
15666 
15667 	if (canputnext(q)) {
15668 		/* Not flow-controlled, open rwnd */
15669 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
15670 
15671 		/*
15672 		 * Send back a window update immediately if TCP is above
15673 		 * ESTABLISHED state and the increase of the rcv window
15674 		 * that the other side knows is at least 1 MSS after flow
15675 		 * control is lifted.
15676 		 */
15677 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15678 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
15679 			tcp_xmit_ctl(NULL, tcp,
15680 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15681 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15682 		}
15683 	}
15684 }
15685 
15686 /*
15687  * The read side service routine is called mostly when we get back-enabled as a
15688  * result of flow control relief.  Since we don't actually queue anything in
15689  * TCP, we have no data to send out of here.  What we do is clear the receive
15690  * window, and send out a window update.
15691  */
15692 static void
15693 tcp_rsrv(queue_t *q)
15694 {
15695 	conn_t		*connp = Q_TO_CONN(q);
15696 	tcp_t		*tcp = connp->conn_tcp;
15697 	mblk_t		*mp;
15698 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15699 
15700 	/* No code does a putq on the read side */
15701 	ASSERT(q->q_first == NULL);
15702 
15703 	/* Nothing to do for the default queue */
15704 	if (q == tcps->tcps_g_q) {
15705 		return;
15706 	}
15707 
15708 	/*
15709 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15710 	 * been run.  So just return.
15711 	 */
15712 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15713 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15714 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15715 		return;
15716 	}
15717 	tcp->tcp_rsrv_mp = NULL;
15718 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15719 
15720 	CONN_INC_REF(connp);
15721 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15722 	    SQ_PROCESS, SQTAG_TCP_RSRV);
15723 }
15724 
15725 /*
15726  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15727  * We do not allow the receive window to shrink.  After setting rwnd,
15728  * set the flow control hiwat of the stream.
15729  *
15730  * This function is called in 2 cases:
15731  *
15732  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15733  *    connection (passive open) and in tcp_rput_data() for active connect.
15734  *    This is called after tcp_mss_set() when the desired MSS value is known.
15735  *    This makes sure that our window size is a mutiple of the other side's
15736  *    MSS.
15737  * 2) Handling SO_RCVBUF option.
15738  *
15739  * It is ASSUMED that the requested size is a multiple of the current MSS.
15740  *
15741  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15742  * user requests so.
15743  */
15744 int
15745 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15746 {
15747 	uint32_t	mss = tcp->tcp_mss;
15748 	uint32_t	old_max_rwnd;
15749 	uint32_t	max_transmittable_rwnd;
15750 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15751 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15752 
15753 	/*
15754 	 * Insist on a receive window that is at least
15755 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15756 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15757 	 * and delayed acknowledgement.
15758 	 */
15759 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
15760 
15761 	if (tcp->tcp_fused) {
15762 		size_t sth_hiwat;
15763 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15764 
15765 		ASSERT(peer_tcp != NULL);
15766 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15767 		if (!tcp_detached) {
15768 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15769 			    sth_hiwat);
15770 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
15771 		}
15772 
15773 		/*
15774 		 * In the fusion case, the maxpsz stream head value of
15775 		 * our peer is set according to its send buffer size
15776 		 * and our receive buffer size; since the latter may
15777 		 * have changed we need to update the peer's maxpsz.
15778 		 */
15779 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15780 		return (sth_hiwat);
15781 	}
15782 
15783 	if (tcp_detached) {
15784 		old_max_rwnd = tcp->tcp_rwnd;
15785 	} else {
15786 		old_max_rwnd = tcp->tcp_recv_hiwater;
15787 	}
15788 
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 	tcp->tcp_recv_hiwater = rwnd;
15841 
15842 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15843 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15844 		tcp->tcp_cwnd_max = rwnd;
15845 
15846 	if (tcp_detached)
15847 		return (rwnd);
15848 
15849 	tcp_set_recv_threshold(tcp, rwnd >> 3);
15850 
15851 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp, rwnd);
15852 	return (rwnd);
15853 }
15854 
15855 /*
15856  * Return SNMP stuff in buffer in mpdata.
15857  */
15858 mblk_t *
15859 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15860 {
15861 	mblk_t			*mpdata;
15862 	mblk_t			*mp_conn_ctl = NULL;
15863 	mblk_t			*mp_conn_tail;
15864 	mblk_t			*mp_attr_ctl = NULL;
15865 	mblk_t			*mp_attr_tail;
15866 	mblk_t			*mp6_conn_ctl = NULL;
15867 	mblk_t			*mp6_conn_tail;
15868 	mblk_t			*mp6_attr_ctl = NULL;
15869 	mblk_t			*mp6_attr_tail;
15870 	struct opthdr		*optp;
15871 	mib2_tcpConnEntry_t	tce;
15872 	mib2_tcp6ConnEntry_t	tce6;
15873 	mib2_transportMLPEntry_t mlp;
15874 	connf_t			*connfp;
15875 	int			i;
15876 	boolean_t 		ispriv;
15877 	zoneid_t 		zoneid;
15878 	int			v4_conn_idx;
15879 	int			v6_conn_idx;
15880 	conn_t			*connp = Q_TO_CONN(q);
15881 	tcp_stack_t		*tcps;
15882 	ip_stack_t		*ipst;
15883 	mblk_t			*mp2ctl;
15884 
15885 	/*
15886 	 * make a copy of the original message
15887 	 */
15888 	mp2ctl = copymsg(mpctl);
15889 
15890 	if (mpctl == NULL ||
15891 	    (mpdata = mpctl->b_cont) == NULL ||
15892 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15893 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
15894 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
15895 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
15896 		freemsg(mp_conn_ctl);
15897 		freemsg(mp_attr_ctl);
15898 		freemsg(mp6_conn_ctl);
15899 		freemsg(mp6_attr_ctl);
15900 		freemsg(mpctl);
15901 		freemsg(mp2ctl);
15902 		return (NULL);
15903 	}
15904 
15905 	ipst = connp->conn_netstack->netstack_ip;
15906 	tcps = connp->conn_netstack->netstack_tcp;
15907 
15908 	/* build table of connections -- need count in fixed part */
15909 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
15910 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
15911 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
15912 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
15913 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
15914 
15915 	ispriv =
15916 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15917 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15918 
15919 	v4_conn_idx = v6_conn_idx = 0;
15920 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
15921 
15922 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15923 		ipst = tcps->tcps_netstack->netstack_ip;
15924 
15925 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
15926 
15927 		connp = NULL;
15928 
15929 		while ((connp =
15930 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15931 			tcp_t *tcp;
15932 			boolean_t needattr;
15933 
15934 			if (connp->conn_zoneid != zoneid)
15935 				continue;	/* not in this zone */
15936 
15937 			tcp = connp->conn_tcp;
15938 			UPDATE_MIB(&tcps->tcps_mib,
15939 			    tcpHCInSegs, tcp->tcp_ibsegs);
15940 			tcp->tcp_ibsegs = 0;
15941 			UPDATE_MIB(&tcps->tcps_mib,
15942 			    tcpHCOutSegs, tcp->tcp_obsegs);
15943 			tcp->tcp_obsegs = 0;
15944 
15945 			tce6.tcp6ConnState = tce.tcpConnState =
15946 			    tcp_snmp_state(tcp);
15947 			if (tce.tcpConnState == MIB2_TCP_established ||
15948 			    tce.tcpConnState == MIB2_TCP_closeWait)
15949 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
15950 
15951 			needattr = B_FALSE;
15952 			bzero(&mlp, sizeof (mlp));
15953 			if (connp->conn_mlp_type != mlptSingle) {
15954 				if (connp->conn_mlp_type == mlptShared ||
15955 				    connp->conn_mlp_type == mlptBoth)
15956 					mlp.tme_flags |= MIB2_TMEF_SHARED;
15957 				if (connp->conn_mlp_type == mlptPrivate ||
15958 				    connp->conn_mlp_type == mlptBoth)
15959 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
15960 				needattr = B_TRUE;
15961 			}
15962 			if (connp->conn_anon_mlp) {
15963 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
15964 				needattr = B_TRUE;
15965 			}
15966 			if (connp->conn_mac_exempt) {
15967 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
15968 				needattr = B_TRUE;
15969 			}
15970 			if (connp->conn_fully_bound &&
15971 			    connp->conn_effective_cred != NULL) {
15972 				ts_label_t *tsl;
15973 
15974 				tsl = crgetlabel(connp->conn_effective_cred);
15975 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
15976 				mlp.tme_doi = label2doi(tsl);
15977 				mlp.tme_label = *label2bslabel(tsl);
15978 				needattr = B_TRUE;
15979 			}
15980 
15981 			/* Create a message to report on IPv6 entries */
15982 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15983 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15984 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15985 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15986 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15987 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15988 			/* Don't want just anybody seeing these... */
15989 			if (ispriv) {
15990 				tce6.tcp6ConnEntryInfo.ce_snxt =
15991 				    tcp->tcp_snxt;
15992 				tce6.tcp6ConnEntryInfo.ce_suna =
15993 				    tcp->tcp_suna;
15994 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15995 				    tcp->tcp_rnxt;
15996 				tce6.tcp6ConnEntryInfo.ce_rack =
15997 				    tcp->tcp_rack;
15998 			} else {
15999 				/*
16000 				 * Netstat, unfortunately, uses this to
16001 				 * get send/receive queue sizes.  How to fix?
16002 				 * Why not compute the difference only?
16003 				 */
16004 				tce6.tcp6ConnEntryInfo.ce_snxt =
16005 				    tcp->tcp_snxt - tcp->tcp_suna;
16006 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16007 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16008 				    tcp->tcp_rnxt - tcp->tcp_rack;
16009 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16010 			}
16011 
16012 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16013 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16014 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16015 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16016 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16017 
16018 			tce6.tcp6ConnCreationProcess =
16019 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16020 			    tcp->tcp_cpid;
16021 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16022 
16023 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16024 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16025 
16026 			mlp.tme_connidx = v6_conn_idx++;
16027 			if (needattr)
16028 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16029 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16030 			}
16031 			/*
16032 			 * Create an IPv4 table entry for IPv4 entries and also
16033 			 * for IPv6 entries which are bound to in6addr_any
16034 			 * but don't have IPV6_V6ONLY set.
16035 			 * (i.e. anything an IPv4 peer could connect to)
16036 			 */
16037 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16038 			    (tcp->tcp_state <= TCPS_LISTEN &&
16039 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16040 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16041 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16042 					tce.tcpConnRemAddress = INADDR_ANY;
16043 					tce.tcpConnLocalAddress = INADDR_ANY;
16044 				} else {
16045 					tce.tcpConnRemAddress =
16046 					    tcp->tcp_remote;
16047 					tce.tcpConnLocalAddress =
16048 					    tcp->tcp_ip_src;
16049 				}
16050 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16051 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16052 				/* Don't want just anybody seeing these... */
16053 				if (ispriv) {
16054 					tce.tcpConnEntryInfo.ce_snxt =
16055 					    tcp->tcp_snxt;
16056 					tce.tcpConnEntryInfo.ce_suna =
16057 					    tcp->tcp_suna;
16058 					tce.tcpConnEntryInfo.ce_rnxt =
16059 					    tcp->tcp_rnxt;
16060 					tce.tcpConnEntryInfo.ce_rack =
16061 					    tcp->tcp_rack;
16062 				} else {
16063 					/*
16064 					 * Netstat, unfortunately, uses this to
16065 					 * get send/receive queue sizes.  How
16066 					 * to fix?
16067 					 * Why not compute the difference only?
16068 					 */
16069 					tce.tcpConnEntryInfo.ce_snxt =
16070 					    tcp->tcp_snxt - tcp->tcp_suna;
16071 					tce.tcpConnEntryInfo.ce_suna = 0;
16072 					tce.tcpConnEntryInfo.ce_rnxt =
16073 					    tcp->tcp_rnxt - tcp->tcp_rack;
16074 					tce.tcpConnEntryInfo.ce_rack = 0;
16075 				}
16076 
16077 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16078 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16079 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16080 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16081 				tce.tcpConnEntryInfo.ce_state =
16082 				    tcp->tcp_state;
16083 
16084 				tce.tcpConnCreationProcess =
16085 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16086 				    tcp->tcp_cpid;
16087 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16088 
16089 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16090 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16091 
16092 				mlp.tme_connidx = v4_conn_idx++;
16093 				if (needattr)
16094 					(void) snmp_append_data2(
16095 					    mp_attr_ctl->b_cont,
16096 					    &mp_attr_tail, (char *)&mlp,
16097 					    sizeof (mlp));
16098 			}
16099 		}
16100 	}
16101 
16102 	/* fixed length structure for IPv4 and IPv6 counters */
16103 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16104 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16105 	    sizeof (mib2_tcp6ConnEntry_t));
16106 	/* synchronize 32- and 64-bit counters */
16107 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16108 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16109 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16110 	optp->level = MIB2_TCP;
16111 	optp->name = 0;
16112 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16113 	    sizeof (tcps->tcps_mib));
16114 	optp->len = msgdsize(mpdata);
16115 	qreply(q, mpctl);
16116 
16117 	/* table of connections... */
16118 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16119 	    sizeof (struct T_optmgmt_ack)];
16120 	optp->level = MIB2_TCP;
16121 	optp->name = MIB2_TCP_CONN;
16122 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16123 	qreply(q, mp_conn_ctl);
16124 
16125 	/* table of MLP attributes... */
16126 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16127 	    sizeof (struct T_optmgmt_ack)];
16128 	optp->level = MIB2_TCP;
16129 	optp->name = EXPER_XPORT_MLP;
16130 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16131 	if (optp->len == 0)
16132 		freemsg(mp_attr_ctl);
16133 	else
16134 		qreply(q, mp_attr_ctl);
16135 
16136 	/* table of IPv6 connections... */
16137 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16138 	    sizeof (struct T_optmgmt_ack)];
16139 	optp->level = MIB2_TCP6;
16140 	optp->name = MIB2_TCP6_CONN;
16141 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16142 	qreply(q, mp6_conn_ctl);
16143 
16144 	/* table of IPv6 MLP attributes... */
16145 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16146 	    sizeof (struct T_optmgmt_ack)];
16147 	optp->level = MIB2_TCP6;
16148 	optp->name = EXPER_XPORT_MLP;
16149 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16150 	if (optp->len == 0)
16151 		freemsg(mp6_attr_ctl);
16152 	else
16153 		qreply(q, mp6_attr_ctl);
16154 	return (mp2ctl);
16155 }
16156 
16157 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16158 /* ARGSUSED */
16159 int
16160 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16161 {
16162 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16163 
16164 	switch (level) {
16165 	case MIB2_TCP:
16166 		switch (name) {
16167 		case 13:
16168 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16169 				return (0);
16170 			/* TODO: delete entry defined by tce */
16171 			return (1);
16172 		default:
16173 			return (0);
16174 		}
16175 	default:
16176 		return (1);
16177 	}
16178 }
16179 
16180 /* Translate TCP state to MIB2 TCP state. */
16181 static int
16182 tcp_snmp_state(tcp_t *tcp)
16183 {
16184 	if (tcp == NULL)
16185 		return (0);
16186 
16187 	switch (tcp->tcp_state) {
16188 	case TCPS_CLOSED:
16189 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16190 	case TCPS_BOUND:
16191 		return (MIB2_TCP_closed);
16192 	case TCPS_LISTEN:
16193 		return (MIB2_TCP_listen);
16194 	case TCPS_SYN_SENT:
16195 		return (MIB2_TCP_synSent);
16196 	case TCPS_SYN_RCVD:
16197 		return (MIB2_TCP_synReceived);
16198 	case TCPS_ESTABLISHED:
16199 		return (MIB2_TCP_established);
16200 	case TCPS_CLOSE_WAIT:
16201 		return (MIB2_TCP_closeWait);
16202 	case TCPS_FIN_WAIT_1:
16203 		return (MIB2_TCP_finWait1);
16204 	case TCPS_CLOSING:
16205 		return (MIB2_TCP_closing);
16206 	case TCPS_LAST_ACK:
16207 		return (MIB2_TCP_lastAck);
16208 	case TCPS_FIN_WAIT_2:
16209 		return (MIB2_TCP_finWait2);
16210 	case TCPS_TIME_WAIT:
16211 		return (MIB2_TCP_timeWait);
16212 	default:
16213 		return (0);
16214 	}
16215 }
16216 
16217 /*
16218  * tcp_timer is the timer service routine.  It handles the retransmission,
16219  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16220  * from the state of the tcp instance what kind of action needs to be done
16221  * at the time it is called.
16222  */
16223 static void
16224 tcp_timer(void *arg)
16225 {
16226 	mblk_t		*mp;
16227 	clock_t		first_threshold;
16228 	clock_t		second_threshold;
16229 	clock_t		ms;
16230 	uint32_t	mss;
16231 	conn_t		*connp = (conn_t *)arg;
16232 	tcp_t		*tcp = connp->conn_tcp;
16233 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16234 
16235 	tcp->tcp_timer_tid = 0;
16236 
16237 	if (tcp->tcp_fused)
16238 		return;
16239 
16240 	first_threshold =  tcp->tcp_first_timer_threshold;
16241 	second_threshold = tcp->tcp_second_timer_threshold;
16242 	switch (tcp->tcp_state) {
16243 	case TCPS_IDLE:
16244 	case TCPS_BOUND:
16245 	case TCPS_LISTEN:
16246 		return;
16247 	case TCPS_SYN_RCVD: {
16248 		tcp_t	*listener = tcp->tcp_listener;
16249 
16250 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16251 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16252 			/* it's our first timeout */
16253 			tcp->tcp_syn_rcvd_timeout = 1;
16254 			mutex_enter(&listener->tcp_eager_lock);
16255 			listener->tcp_syn_rcvd_timeout++;
16256 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16257 				/*
16258 				 * Make this eager available for drop if we
16259 				 * need to drop one to accomodate a new
16260 				 * incoming SYN request.
16261 				 */
16262 				MAKE_DROPPABLE(listener, tcp);
16263 			}
16264 			if (!listener->tcp_syn_defense &&
16265 			    (listener->tcp_syn_rcvd_timeout >
16266 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16267 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16268 				/* We may be under attack. Put on a defense. */
16269 				listener->tcp_syn_defense = B_TRUE;
16270 				cmn_err(CE_WARN, "High TCP connect timeout "
16271 				    "rate! System (port %d) may be under a "
16272 				    "SYN flood attack!",
16273 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16274 
16275 				listener->tcp_ip_addr_cache = kmem_zalloc(
16276 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16277 				    KM_NOSLEEP);
16278 			}
16279 			mutex_exit(&listener->tcp_eager_lock);
16280 		} else if (listener != NULL) {
16281 			mutex_enter(&listener->tcp_eager_lock);
16282 			tcp->tcp_syn_rcvd_timeout++;
16283 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16284 			    !tcp->tcp_closemp_used) {
16285 				/*
16286 				 * This is our second timeout. Put the tcp in
16287 				 * the list of droppable eagers to allow it to
16288 				 * be dropped, if needed. We don't check
16289 				 * whether tcp_dontdrop is set or not to
16290 				 * protect ourselve from a SYN attack where a
16291 				 * remote host can spoof itself as one of the
16292 				 * good IP source and continue to hold
16293 				 * resources too long.
16294 				 */
16295 				MAKE_DROPPABLE(listener, tcp);
16296 			}
16297 			mutex_exit(&listener->tcp_eager_lock);
16298 		}
16299 	}
16300 		/* FALLTHRU */
16301 	case TCPS_SYN_SENT:
16302 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16303 		second_threshold = tcp->tcp_second_ctimer_threshold;
16304 		break;
16305 	case TCPS_ESTABLISHED:
16306 	case TCPS_FIN_WAIT_1:
16307 	case TCPS_CLOSING:
16308 	case TCPS_CLOSE_WAIT:
16309 	case TCPS_LAST_ACK:
16310 		/* If we have data to rexmit */
16311 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16312 			clock_t	time_to_wait;
16313 
16314 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16315 			if (!tcp->tcp_xmit_head)
16316 				break;
16317 			time_to_wait = lbolt -
16318 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16319 			time_to_wait = tcp->tcp_rto -
16320 			    TICK_TO_MSEC(time_to_wait);
16321 			/*
16322 			 * If the timer fires too early, 1 clock tick earlier,
16323 			 * restart the timer.
16324 			 */
16325 			if (time_to_wait > msec_per_tick) {
16326 				TCP_STAT(tcps, tcp_timer_fire_early);
16327 				TCP_TIMER_RESTART(tcp, time_to_wait);
16328 				return;
16329 			}
16330 			/*
16331 			 * When we probe zero windows, we force the swnd open.
16332 			 * If our peer acks with a closed window swnd will be
16333 			 * set to zero by tcp_rput(). As long as we are
16334 			 * receiving acks tcp_rput will
16335 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16336 			 * first and second interval actions.  NOTE: the timer
16337 			 * interval is allowed to continue its exponential
16338 			 * backoff.
16339 			 */
16340 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16341 				if (tcp->tcp_debug) {
16342 					(void) strlog(TCP_MOD_ID, 0, 1,
16343 					    SL_TRACE, "tcp_timer: zero win");
16344 				}
16345 			} else {
16346 				/*
16347 				 * After retransmission, we need to do
16348 				 * slow start.  Set the ssthresh to one
16349 				 * half of current effective window and
16350 				 * cwnd to one MSS.  Also reset
16351 				 * tcp_cwnd_cnt.
16352 				 *
16353 				 * Note that if tcp_ssthresh is reduced because
16354 				 * of ECN, do not reduce it again unless it is
16355 				 * already one window of data away (tcp_cwr
16356 				 * should then be cleared) or this is a
16357 				 * timeout for a retransmitted segment.
16358 				 */
16359 				uint32_t npkt;
16360 
16361 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16362 					npkt = ((tcp->tcp_timer_backoff ?
16363 					    tcp->tcp_cwnd_ssthresh :
16364 					    tcp->tcp_snxt -
16365 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16366 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16367 					    tcp->tcp_mss;
16368 				}
16369 				tcp->tcp_cwnd = tcp->tcp_mss;
16370 				tcp->tcp_cwnd_cnt = 0;
16371 				if (tcp->tcp_ecn_ok) {
16372 					tcp->tcp_cwr = B_TRUE;
16373 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16374 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16375 				}
16376 			}
16377 			break;
16378 		}
16379 		/*
16380 		 * We have something to send yet we cannot send.  The
16381 		 * reason can be:
16382 		 *
16383 		 * 1. Zero send window: we need to do zero window probe.
16384 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16385 		 * segments.
16386 		 * 3. SWS avoidance: receiver may have shrunk window,
16387 		 * reset our knowledge.
16388 		 *
16389 		 * Note that condition 2 can happen with either 1 or
16390 		 * 3.  But 1 and 3 are exclusive.
16391 		 */
16392 		if (tcp->tcp_unsent != 0) {
16393 			if (tcp->tcp_cwnd == 0) {
16394 				/*
16395 				 * Set tcp_cwnd to 1 MSS so that a
16396 				 * new segment can be sent out.  We
16397 				 * are "clocking out" new data when
16398 				 * the network is really congested.
16399 				 */
16400 				ASSERT(tcp->tcp_ecn_ok);
16401 				tcp->tcp_cwnd = tcp->tcp_mss;
16402 			}
16403 			if (tcp->tcp_swnd == 0) {
16404 				/* Extend window for zero window probe */
16405 				tcp->tcp_swnd++;
16406 				tcp->tcp_zero_win_probe = B_TRUE;
16407 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
16408 			} else {
16409 				/*
16410 				 * Handle timeout from sender SWS avoidance.
16411 				 * Reset our knowledge of the max send window
16412 				 * since the receiver might have reduced its
16413 				 * receive buffer.  Avoid setting tcp_max_swnd
16414 				 * to one since that will essentially disable
16415 				 * the SWS checks.
16416 				 *
16417 				 * Note that since we don't have a SWS
16418 				 * state variable, if the timeout is set
16419 				 * for ECN but not for SWS, this
16420 				 * code will also be executed.  This is
16421 				 * fine as tcp_max_swnd is updated
16422 				 * constantly and it will not affect
16423 				 * anything.
16424 				 */
16425 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16426 			}
16427 			tcp_wput_data(tcp, NULL, B_FALSE);
16428 			return;
16429 		}
16430 		/* Is there a FIN that needs to be to re retransmitted? */
16431 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16432 		    !tcp->tcp_fin_acked)
16433 			break;
16434 		/* Nothing to do, return without restarting timer. */
16435 		TCP_STAT(tcps, tcp_timer_fire_miss);
16436 		return;
16437 	case TCPS_FIN_WAIT_2:
16438 		/*
16439 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16440 		 * We waited some time for for peer's FIN, but it hasn't
16441 		 * arrived.  We flush the connection now to avoid
16442 		 * case where the peer has rebooted.
16443 		 */
16444 		if (TCP_IS_DETACHED(tcp)) {
16445 			(void) tcp_clean_death(tcp, 0, 23);
16446 		} else {
16447 			TCP_TIMER_RESTART(tcp,
16448 			    tcps->tcps_fin_wait_2_flush_interval);
16449 		}
16450 		return;
16451 	case TCPS_TIME_WAIT:
16452 		(void) tcp_clean_death(tcp, 0, 24);
16453 		return;
16454 	default:
16455 		if (tcp->tcp_debug) {
16456 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16457 			    "tcp_timer: strange state (%d) %s",
16458 			    tcp->tcp_state, tcp_display(tcp, NULL,
16459 			    DISP_PORT_ONLY));
16460 		}
16461 		return;
16462 	}
16463 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16464 		/*
16465 		 * For zero window probe, we need to send indefinitely,
16466 		 * unless we have not heard from the other side for some
16467 		 * time...
16468 		 */
16469 		if ((tcp->tcp_zero_win_probe == 0) ||
16470 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16471 		    second_threshold)) {
16472 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
16473 			/*
16474 			 * If TCP is in SYN_RCVD state, send back a
16475 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16476 			 * should be zero in TCPS_SYN_RCVD state.
16477 			 */
16478 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16479 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16480 				    "in SYN_RCVD",
16481 				    tcp, tcp->tcp_snxt,
16482 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16483 			}
16484 			(void) tcp_clean_death(tcp,
16485 			    tcp->tcp_client_errno ?
16486 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16487 			return;
16488 		} else {
16489 			/*
16490 			 * Set tcp_ms_we_have_waited to second_threshold
16491 			 * so that in next timeout, we will do the above
16492 			 * check (lbolt - tcp_last_recv_time).  This is
16493 			 * also to avoid overflow.
16494 			 *
16495 			 * We don't need to decrement tcp_timer_backoff
16496 			 * to avoid overflow because it will be decremented
16497 			 * later if new timeout value is greater than
16498 			 * tcp_rexmit_interval_max.  In the case when
16499 			 * tcp_rexmit_interval_max is greater than
16500 			 * second_threshold, it means that we will wait
16501 			 * longer than second_threshold to send the next
16502 			 * window probe.
16503 			 */
16504 			tcp->tcp_ms_we_have_waited = second_threshold;
16505 		}
16506 	} else if (ms > first_threshold) {
16507 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16508 		    tcp->tcp_xmit_head != NULL) {
16509 			tcp->tcp_xmit_head =
16510 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16511 		}
16512 		/*
16513 		 * We have been retransmitting for too long...  The RTT
16514 		 * we calculated is probably incorrect.  Reinitialize it.
16515 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16516 		 * tcp_rtt_update so that we won't accidentally cache a
16517 		 * bad value.  But only do this if this is not a zero
16518 		 * window probe.
16519 		 */
16520 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16521 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16522 			    (tcp->tcp_rtt_sa >> 5);
16523 			tcp->tcp_rtt_sa = 0;
16524 			tcp_ip_notify(tcp);
16525 			tcp->tcp_rtt_update = 0;
16526 		}
16527 	}
16528 	tcp->tcp_timer_backoff++;
16529 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16530 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16531 	    tcps->tcps_rexmit_interval_min) {
16532 		/*
16533 		 * This means the original RTO is tcp_rexmit_interval_min.
16534 		 * So we will use tcp_rexmit_interval_min as the RTO value
16535 		 * and do the backoff.
16536 		 */
16537 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
16538 	} else {
16539 		ms <<= tcp->tcp_timer_backoff;
16540 	}
16541 	if (ms > tcps->tcps_rexmit_interval_max) {
16542 		ms = tcps->tcps_rexmit_interval_max;
16543 		/*
16544 		 * ms is at max, decrement tcp_timer_backoff to avoid
16545 		 * overflow.
16546 		 */
16547 		tcp->tcp_timer_backoff--;
16548 	}
16549 	tcp->tcp_ms_we_have_waited += ms;
16550 	if (tcp->tcp_zero_win_probe == 0) {
16551 		tcp->tcp_rto = ms;
16552 	}
16553 	TCP_TIMER_RESTART(tcp, ms);
16554 	/*
16555 	 * This is after a timeout and tcp_rto is backed off.  Set
16556 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16557 	 * restart the timer with a correct value.
16558 	 */
16559 	tcp->tcp_set_timer = 1;
16560 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16561 	if (mss > tcp->tcp_mss)
16562 		mss = tcp->tcp_mss;
16563 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16564 		mss = tcp->tcp_swnd;
16565 
16566 	if ((mp = tcp->tcp_xmit_head) != NULL)
16567 		mp->b_prev = (mblk_t *)lbolt;
16568 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16569 	    B_TRUE);
16570 
16571 	/*
16572 	 * When slow start after retransmission begins, start with
16573 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16574 	 * start phase.  tcp_snd_burst controls how many segments
16575 	 * can be sent because of an ack.
16576 	 */
16577 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16578 	tcp->tcp_snd_burst = TCP_CWND_SS;
16579 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16580 	    (tcp->tcp_unsent == 0)) {
16581 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16582 	} else {
16583 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16584 	}
16585 	tcp->tcp_rexmit = B_TRUE;
16586 	tcp->tcp_dupack_cnt = 0;
16587 
16588 	/*
16589 	 * Remove all rexmit SACK blk to start from fresh.
16590 	 */
16591 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
16592 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
16593 	if (mp == NULL) {
16594 		return;
16595 	}
16596 	/*
16597 	 * Attach credentials to retransmitted initial SYNs.
16598 	 * In theory we should use the credentials from the connect()
16599 	 * call to ensure that getpeerucred() on the peer will be correct.
16600 	 * But we assume that SYN's are not dropped for loopback connections.
16601 	 */
16602 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16603 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp), tcp->tcp_cpid);
16604 	}
16605 
16606 	tcp->tcp_csuna = tcp->tcp_snxt;
16607 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
16608 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
16609 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16610 
16611 }
16612 
16613 static int
16614 tcp_do_unbind(conn_t *connp)
16615 {
16616 	tcp_t *tcp = connp->conn_tcp;
16617 	int error = 0;
16618 
16619 	switch (tcp->tcp_state) {
16620 	case TCPS_BOUND:
16621 	case TCPS_LISTEN:
16622 		break;
16623 	default:
16624 		return (-TOUTSTATE);
16625 	}
16626 
16627 	/*
16628 	 * Need to clean up all the eagers since after the unbind, segments
16629 	 * will no longer be delivered to this listener stream.
16630 	 */
16631 	mutex_enter(&tcp->tcp_eager_lock);
16632 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16633 		tcp_eager_cleanup(tcp, 0);
16634 	}
16635 	mutex_exit(&tcp->tcp_eager_lock);
16636 
16637 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16638 		tcp->tcp_ipha->ipha_src = 0;
16639 	} else {
16640 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16641 	}
16642 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16643 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16644 	tcp_bind_hash_remove(tcp);
16645 	tcp->tcp_state = TCPS_IDLE;
16646 	tcp->tcp_mdt = B_FALSE;
16647 
16648 	connp = tcp->tcp_connp;
16649 	connp->conn_mdt_ok = B_FALSE;
16650 	ipcl_hash_remove(connp);
16651 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16652 
16653 	return (error);
16654 }
16655 
16656 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16657 static void
16658 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
16659 {
16660 	int error = tcp_do_unbind(tcp->tcp_connp);
16661 
16662 	if (error > 0) {
16663 		tcp_err_ack(tcp, mp, TSYSERR, error);
16664 	} else if (error < 0) {
16665 		tcp_err_ack(tcp, mp, -error, 0);
16666 	} else {
16667 		/* Send M_FLUSH according to TPI */
16668 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16669 
16670 		mp = mi_tpi_ok_ack_alloc(mp);
16671 		putnext(tcp->tcp_rq, mp);
16672 	}
16673 }
16674 
16675 /*
16676  * Don't let port fall into the privileged range.
16677  * Since the extra privileged ports can be arbitrary we also
16678  * ensure that we exclude those from consideration.
16679  * tcp_g_epriv_ports is not sorted thus we loop over it until
16680  * there are no changes.
16681  *
16682  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16683  * but instead the code relies on:
16684  * - the fact that the address of the array and its size never changes
16685  * - the atomic assignment of the elements of the array
16686  *
16687  * Returns 0 if there are no more ports available.
16688  *
16689  * TS note: skip multilevel ports.
16690  */
16691 static in_port_t
16692 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16693 {
16694 	int i;
16695 	boolean_t restart = B_FALSE;
16696 	tcp_stack_t *tcps = tcp->tcp_tcps;
16697 
16698 	if (random && tcp_random_anon_port != 0) {
16699 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16700 		    sizeof (in_port_t));
16701 		/*
16702 		 * Unless changed by a sys admin, the smallest anon port
16703 		 * is 32768 and the largest anon port is 65535.  It is
16704 		 * very likely (50%) for the random port to be smaller
16705 		 * than the smallest anon port.  When that happens,
16706 		 * add port % (anon port range) to the smallest anon
16707 		 * port to get the random port.  It should fall into the
16708 		 * valid anon port range.
16709 		 */
16710 		if (port < tcps->tcps_smallest_anon_port) {
16711 			port = tcps->tcps_smallest_anon_port +
16712 			    port % (tcps->tcps_largest_anon_port -
16713 			    tcps->tcps_smallest_anon_port);
16714 		}
16715 	}
16716 
16717 retry:
16718 	if (port < tcps->tcps_smallest_anon_port)
16719 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16720 
16721 	if (port > tcps->tcps_largest_anon_port) {
16722 		if (restart)
16723 			return (0);
16724 		restart = B_TRUE;
16725 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16726 	}
16727 
16728 	if (port < tcps->tcps_smallest_nonpriv_port)
16729 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
16730 
16731 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
16732 		if (port == tcps->tcps_g_epriv_ports[i]) {
16733 			port++;
16734 			/*
16735 			 * Make sure whether the port is in the
16736 			 * valid range.
16737 			 */
16738 			goto retry;
16739 		}
16740 	}
16741 	if (is_system_labeled() &&
16742 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
16743 	    IPPROTO_TCP, B_TRUE)) != 0) {
16744 		port = i;
16745 		goto retry;
16746 	}
16747 	return (port);
16748 }
16749 
16750 /*
16751  * Return the next anonymous port in the privileged port range for
16752  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16753  * downwards.  This is the same behavior as documented in the userland
16754  * library call rresvport(3N).
16755  *
16756  * TS note: skip multilevel ports.
16757  */
16758 static in_port_t
16759 tcp_get_next_priv_port(const tcp_t *tcp)
16760 {
16761 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16762 	in_port_t nextport;
16763 	boolean_t restart = B_FALSE;
16764 	tcp_stack_t *tcps = tcp->tcp_tcps;
16765 retry:
16766 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
16767 	    next_priv_port >= IPPORT_RESERVED) {
16768 		next_priv_port = IPPORT_RESERVED - 1;
16769 		if (restart)
16770 			return (0);
16771 		restart = B_TRUE;
16772 	}
16773 	if (is_system_labeled() &&
16774 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
16775 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
16776 		next_priv_port = nextport;
16777 		goto retry;
16778 	}
16779 	return (next_priv_port--);
16780 }
16781 
16782 /* The write side r/w procedure. */
16783 
16784 #if CCS_STATS
16785 struct {
16786 	struct {
16787 		int64_t count, bytes;
16788 	} tot, hit;
16789 } wrw_stats;
16790 #endif
16791 
16792 /*
16793  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16794  * messages.
16795  */
16796 /* ARGSUSED */
16797 static void
16798 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16799 {
16800 	conn_t	*connp = (conn_t *)arg;
16801 	tcp_t	*tcp = connp->conn_tcp;
16802 	queue_t	*q = tcp->tcp_wq;
16803 
16804 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16805 	/*
16806 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16807 	 * Once the close starts, streamhead and sockfs will not let any data
16808 	 * packets come down (close ensures that there are no threads using the
16809 	 * queue and no new threads will come down) but since qprocsoff()
16810 	 * hasn't happened yet, a M_FLUSH or some non data message might
16811 	 * get reflected back (in response to our own FLUSHRW) and get
16812 	 * processed after tcp_close() is done. The conn would still be valid
16813 	 * because a ref would have added but we need to check the state
16814 	 * before actually processing the packet.
16815 	 */
16816 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16817 		freemsg(mp);
16818 		return;
16819 	}
16820 
16821 	switch (DB_TYPE(mp)) {
16822 	case M_IOCDATA:
16823 		tcp_wput_iocdata(tcp, mp);
16824 		break;
16825 	case M_FLUSH:
16826 		tcp_wput_flush(tcp, mp);
16827 		break;
16828 	default:
16829 		CALL_IP_WPUT(connp, q, mp);
16830 		break;
16831 	}
16832 }
16833 
16834 /*
16835  * The TCP fast path write put procedure.
16836  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16837  */
16838 /* ARGSUSED */
16839 void
16840 tcp_output(void *arg, mblk_t *mp, void *arg2)
16841 {
16842 	int		len;
16843 	int		hdrlen;
16844 	int		plen;
16845 	mblk_t		*mp1;
16846 	uchar_t		*rptr;
16847 	uint32_t	snxt;
16848 	tcph_t		*tcph;
16849 	struct datab	*db;
16850 	uint32_t	suna;
16851 	uint32_t	mss;
16852 	ipaddr_t	*dst;
16853 	ipaddr_t	*src;
16854 	uint32_t	sum;
16855 	int		usable;
16856 	conn_t		*connp = (conn_t *)arg;
16857 	tcp_t		*tcp = connp->conn_tcp;
16858 	uint32_t	msize;
16859 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16860 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
16861 
16862 	/*
16863 	 * Try and ASSERT the minimum possible references on the
16864 	 * conn early enough. Since we are executing on write side,
16865 	 * the connection is obviously not detached and that means
16866 	 * there is a ref each for TCP and IP. Since we are behind
16867 	 * the squeue, the minimum references needed are 3. If the
16868 	 * conn is in classifier hash list, there should be an
16869 	 * extra ref for that (we check both the possibilities).
16870 	 */
16871 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16872 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16873 
16874 	ASSERT(DB_TYPE(mp) == M_DATA);
16875 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
16876 
16877 	mutex_enter(&tcp->tcp_non_sq_lock);
16878 	tcp->tcp_squeue_bytes -= msize;
16879 	mutex_exit(&tcp->tcp_non_sq_lock);
16880 
16881 	/* Check to see if this connection wants to be re-fused. */
16882 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
16883 		if (tcp->tcp_ipversion == IPV4_VERSION) {
16884 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
16885 			    &tcp->tcp_saved_tcph);
16886 		} else {
16887 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
16888 			    &tcp->tcp_saved_tcph);
16889 		}
16890 	}
16891 	/* Bypass tcp protocol for fused tcp loopback */
16892 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
16893 		return;
16894 
16895 	mss = tcp->tcp_mss;
16896 	if (tcp->tcp_xmit_zc_clean)
16897 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16898 
16899 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16900 	len = (int)(mp->b_wptr - mp->b_rptr);
16901 
16902 	/*
16903 	 * Criteria for fast path:
16904 	 *
16905 	 *   1. no unsent data
16906 	 *   2. single mblk in request
16907 	 *   3. connection established
16908 	 *   4. data in mblk
16909 	 *   5. len <= mss
16910 	 *   6. no tcp_valid bits
16911 	 */
16912 	if ((tcp->tcp_unsent != 0) ||
16913 	    (tcp->tcp_cork) ||
16914 	    (mp->b_cont != NULL) ||
16915 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16916 	    (len == 0) ||
16917 	    (len > mss) ||
16918 	    (tcp->tcp_valid_bits != 0)) {
16919 		tcp_wput_data(tcp, mp, B_FALSE);
16920 		return;
16921 	}
16922 
16923 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16924 	ASSERT(tcp->tcp_fin_sent == 0);
16925 
16926 	/* queue new packet onto retransmission queue */
16927 	if (tcp->tcp_xmit_head == NULL) {
16928 		tcp->tcp_xmit_head = mp;
16929 	} else {
16930 		tcp->tcp_xmit_last->b_cont = mp;
16931 	}
16932 	tcp->tcp_xmit_last = mp;
16933 	tcp->tcp_xmit_tail = mp;
16934 
16935 	/* find out how much we can send */
16936 	/* BEGIN CSTYLED */
16937 	/*
16938 	 *    un-acked	   usable
16939 	 *  |--------------|-----------------|
16940 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
16941 	 */
16942 	/* END CSTYLED */
16943 
16944 	/* start sending from tcp_snxt */
16945 	snxt = tcp->tcp_snxt;
16946 
16947 	/*
16948 	 * Check to see if this connection has been idled for some
16949 	 * time and no ACK is expected.  If it is, we need to slow
16950 	 * start again to get back the connection's "self-clock" as
16951 	 * described in VJ's paper.
16952 	 *
16953 	 * Refer to the comment in tcp_mss_set() for the calculation
16954 	 * of tcp_cwnd after idle.
16955 	 */
16956 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16957 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16958 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
16959 	}
16960 
16961 	usable = tcp->tcp_swnd;		/* tcp window size */
16962 	if (usable > tcp->tcp_cwnd)
16963 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16964 	usable -= snxt;		/* subtract stuff already sent */
16965 	suna = tcp->tcp_suna;
16966 	usable += suna;
16967 	/* usable can be < 0 if the congestion window is smaller */
16968 	if (len > usable) {
16969 		/* Can't send complete M_DATA in one shot */
16970 		goto slow;
16971 	}
16972 
16973 	mutex_enter(&tcp->tcp_non_sq_lock);
16974 	if (tcp->tcp_flow_stopped &&
16975 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16976 		tcp_clrqfull(tcp);
16977 	}
16978 	mutex_exit(&tcp->tcp_non_sq_lock);
16979 
16980 	/*
16981 	 * determine if anything to send (Nagle).
16982 	 *
16983 	 *   1. len < tcp_mss (i.e. small)
16984 	 *   2. unacknowledged data present
16985 	 *   3. len < nagle limit
16986 	 *   4. last packet sent < nagle limit (previous packet sent)
16987 	 */
16988 	if ((len < mss) && (snxt != suna) &&
16989 	    (len < (int)tcp->tcp_naglim) &&
16990 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
16991 		/*
16992 		 * This was the first unsent packet and normally
16993 		 * mss < xmit_hiwater so there is no need to worry
16994 		 * about flow control. The next packet will go
16995 		 * through the flow control check in tcp_wput_data().
16996 		 */
16997 		/* leftover work from above */
16998 		tcp->tcp_unsent = len;
16999 		tcp->tcp_xmit_tail_unsent = len;
17000 
17001 		return;
17002 	}
17003 
17004 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17005 
17006 	if (snxt == suna) {
17007 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17008 	}
17009 
17010 	/* we have always sent something */
17011 	tcp->tcp_rack_cnt = 0;
17012 
17013 	tcp->tcp_snxt = snxt + len;
17014 	tcp->tcp_rack = tcp->tcp_rnxt;
17015 
17016 	if ((mp1 = dupb(mp)) == 0)
17017 		goto no_memory;
17018 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17019 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17020 
17021 	/* adjust tcp header information */
17022 	tcph = tcp->tcp_tcph;
17023 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17024 
17025 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17026 	sum = (sum >> 16) + (sum & 0xFFFF);
17027 	U16_TO_ABE16(sum, tcph->th_sum);
17028 
17029 	U32_TO_ABE32(snxt, tcph->th_seq);
17030 
17031 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17032 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17033 	BUMP_LOCAL(tcp->tcp_obsegs);
17034 
17035 	/* Update the latest receive window size in TCP header. */
17036 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17037 	    tcph->th_win);
17038 
17039 	tcp->tcp_last_sent_len = (ushort_t)len;
17040 
17041 	plen = len + tcp->tcp_hdr_len;
17042 
17043 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17044 		tcp->tcp_ipha->ipha_length = htons(plen);
17045 	} else {
17046 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17047 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17048 	}
17049 
17050 	/* see if we need to allocate a mblk for the headers */
17051 	hdrlen = tcp->tcp_hdr_len;
17052 	rptr = mp1->b_rptr - hdrlen;
17053 	db = mp1->b_datap;
17054 	if ((db->db_ref != 2) || rptr < db->db_base ||
17055 	    (!OK_32PTR(rptr))) {
17056 		/* NOTE: we assume allocb returns an OK_32PTR */
17057 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17058 		    tcps->tcps_wroff_xtra, BPRI_MED);
17059 		if (!mp) {
17060 			freemsg(mp1);
17061 			goto no_memory;
17062 		}
17063 		mp->b_cont = mp1;
17064 		mp1 = mp;
17065 		/* Leave room for Link Level header */
17066 		/* hdrlen = tcp->tcp_hdr_len; */
17067 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17068 		mp1->b_wptr = &rptr[hdrlen];
17069 	}
17070 	mp1->b_rptr = rptr;
17071 
17072 	/* Fill in the timestamp option. */
17073 	if (tcp->tcp_snd_ts_ok) {
17074 		U32_TO_BE32((uint32_t)lbolt,
17075 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17076 		U32_TO_BE32(tcp->tcp_ts_recent,
17077 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17078 	} else {
17079 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17080 	}
17081 
17082 	/* copy header into outgoing packet */
17083 	dst = (ipaddr_t *)rptr;
17084 	src = (ipaddr_t *)tcp->tcp_iphc;
17085 	dst[0] = src[0];
17086 	dst[1] = src[1];
17087 	dst[2] = src[2];
17088 	dst[3] = src[3];
17089 	dst[4] = src[4];
17090 	dst[5] = src[5];
17091 	dst[6] = src[6];
17092 	dst[7] = src[7];
17093 	dst[8] = src[8];
17094 	dst[9] = src[9];
17095 	if (hdrlen -= 40) {
17096 		hdrlen >>= 2;
17097 		dst += 10;
17098 		src += 10;
17099 		do {
17100 			*dst++ = *src++;
17101 		} while (--hdrlen);
17102 	}
17103 
17104 	/*
17105 	 * Set the ECN info in the TCP header.  Note that this
17106 	 * is not the template header.
17107 	 */
17108 	if (tcp->tcp_ecn_ok) {
17109 		SET_ECT(tcp, rptr);
17110 
17111 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17112 		if (tcp->tcp_ecn_echo_on)
17113 			tcph->th_flags[0] |= TH_ECE;
17114 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17115 			tcph->th_flags[0] |= TH_CWR;
17116 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17117 		}
17118 	}
17119 
17120 	if (tcp->tcp_ip_forward_progress) {
17121 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17122 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17123 		tcp->tcp_ip_forward_progress = B_FALSE;
17124 	}
17125 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17126 	return;
17127 
17128 	/*
17129 	 * If we ran out of memory, we pretend to have sent the packet
17130 	 * and that it was lost on the wire.
17131 	 */
17132 no_memory:
17133 	return;
17134 
17135 slow:
17136 	/* leftover work from above */
17137 	tcp->tcp_unsent = len;
17138 	tcp->tcp_xmit_tail_unsent = len;
17139 	tcp_wput_data(tcp, NULL, B_FALSE);
17140 }
17141 
17142 /* ARGSUSED */
17143 void
17144 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17145 {
17146 	conn_t			*connp = (conn_t *)arg;
17147 	tcp_t			*tcp = connp->conn_tcp;
17148 	queue_t			*q = tcp->tcp_rq;
17149 	struct tcp_options	*tcpopt;
17150 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17151 
17152 	/* socket options */
17153 	uint_t 			sopp_flags;
17154 	ssize_t			sopp_rxhiwat;
17155 	ssize_t			sopp_maxblk;
17156 	ushort_t		sopp_wroff;
17157 	ushort_t		sopp_tail;
17158 	ushort_t		sopp_copyopt;
17159 
17160 	tcpopt = (struct tcp_options *)mp->b_rptr;
17161 
17162 	/*
17163 	 * Drop the eager's ref on the listener, that was placed when
17164 	 * this eager began life in tcp_conn_request.
17165 	 */
17166 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17167 	if (IPCL_IS_NONSTR(connp)) {
17168 		/* Safe to free conn_ind message */
17169 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17170 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17171 	}
17172 
17173 	tcp->tcp_detached = B_FALSE;
17174 
17175 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17176 		/*
17177 		 * Someone blewoff the eager before we could finish
17178 		 * the accept.
17179 		 *
17180 		 * The only reason eager exists it because we put in
17181 		 * a ref on it when conn ind went up. We need to send
17182 		 * a disconnect indication up while the last reference
17183 		 * on the eager will be dropped by the squeue when we
17184 		 * return.
17185 		 */
17186 		ASSERT(tcp->tcp_listener == NULL);
17187 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17188 			if (IPCL_IS_NONSTR(connp)) {
17189 				ASSERT(tcp->tcp_issocket);
17190 				(*connp->conn_upcalls->su_disconnected)(
17191 				    connp->conn_upper_handle, tcp->tcp_connid,
17192 				    ECONNREFUSED);
17193 				freemsg(mp);
17194 			} else {
17195 				struct	T_discon_ind	*tdi;
17196 
17197 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17198 				/*
17199 				 * Let us reuse the incoming mblk to avoid
17200 				 * memory allocation failure problems. We know
17201 				 * that the size of the incoming mblk i.e.
17202 				 * stroptions is greater than sizeof
17203 				 * T_discon_ind. So the reallocb below can't
17204 				 * fail.
17205 				 */
17206 				freemsg(mp->b_cont);
17207 				mp->b_cont = NULL;
17208 				ASSERT(DB_REF(mp) == 1);
17209 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17210 				    B_FALSE);
17211 				ASSERT(mp != NULL);
17212 				DB_TYPE(mp) = M_PROTO;
17213 				((union T_primitives *)mp->b_rptr)->type =
17214 				    T_DISCON_IND;
17215 				tdi = (struct T_discon_ind *)mp->b_rptr;
17216 				if (tcp->tcp_issocket) {
17217 					tdi->DISCON_reason = ECONNREFUSED;
17218 					tdi->SEQ_number = 0;
17219 				} else {
17220 					tdi->DISCON_reason = ENOPROTOOPT;
17221 					tdi->SEQ_number =
17222 					    tcp->tcp_conn_req_seqnum;
17223 				}
17224 				mp->b_wptr = mp->b_rptr +
17225 				    sizeof (struct T_discon_ind);
17226 				putnext(q, mp);
17227 				return;
17228 			}
17229 		}
17230 		if (tcp->tcp_hard_binding) {
17231 			tcp->tcp_hard_binding = B_FALSE;
17232 			tcp->tcp_hard_bound = B_TRUE;
17233 		}
17234 		return;
17235 	}
17236 
17237 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17238 		int boundif = tcpopt->to_boundif;
17239 		uint_t len = sizeof (int);
17240 
17241 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17242 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17243 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17244 	}
17245 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17246 		uint_t on = 1;
17247 		uint_t len = sizeof (uint_t);
17248 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17249 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17250 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17251 	}
17252 
17253 	/*
17254 	 * Set max window size (tcp_recv_hiwater) of the acceptor.
17255 	 */
17256 	if (tcp->tcp_rcv_list == NULL) {
17257 		/*
17258 		 * Recv queue is empty, tcp_rwnd should not have changed.
17259 		 * That means it should be equal to the listener's tcp_rwnd.
17260 		 */
17261 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17262 	} else {
17263 #ifdef DEBUG
17264 		mblk_t *tmp;
17265 		mblk_t	*mp1;
17266 		uint_t	cnt = 0;
17267 
17268 		mp1 = tcp->tcp_rcv_list;
17269 		while ((tmp = mp1) != NULL) {
17270 			mp1 = tmp->b_next;
17271 			cnt += msgdsize(tmp);
17272 		}
17273 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17274 #endif
17275 		/* There is some data, add them back to get the max. */
17276 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17277 	}
17278 	/*
17279 	 * This is the first time we run on the correct
17280 	 * queue after tcp_accept. So fix all the q parameters
17281 	 * here.
17282 	 */
17283 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17284 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17285 
17286 	sopp_rxhiwat = tcp->tcp_fused ?
17287 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17288 	    tcp->tcp_recv_hiwater;
17289 
17290 	/*
17291 	 * Determine what write offset value to use depending on SACK and
17292 	 * whether the endpoint is fused or not.
17293 	 */
17294 	if (tcp->tcp_fused) {
17295 		ASSERT(tcp->tcp_loopback);
17296 		ASSERT(tcp->tcp_loopback_peer != NULL);
17297 		/*
17298 		 * For fused tcp loopback, set the stream head's write
17299 		 * offset value to zero since we won't be needing any room
17300 		 * for TCP/IP headers.  This would also improve performance
17301 		 * since it would reduce the amount of work done by kmem.
17302 		 * Non-fused tcp loopback case is handled separately below.
17303 		 */
17304 		sopp_wroff = 0;
17305 		/*
17306 		 * Update the peer's transmit parameters according to
17307 		 * our recently calculated high water mark value.
17308 		 */
17309 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17310 	} else if (tcp->tcp_snd_sack_ok) {
17311 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17312 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17313 	} else {
17314 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17315 		    tcps->tcps_wroff_xtra);
17316 	}
17317 
17318 	/*
17319 	 * If this is endpoint is handling SSL, then reserve extra
17320 	 * offset and space at the end.
17321 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17322 	 * overriding the previous setting. The extra cost of signing and
17323 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17324 	 * instead of a single contiguous one by the stream head
17325 	 * largely outweighs the statistical reduction of ACKs, when
17326 	 * applicable. The peer will also save on decryption and verification
17327 	 * costs.
17328 	 */
17329 	if (tcp->tcp_kssl_ctx != NULL) {
17330 		sopp_wroff += SSL3_WROFFSET;
17331 
17332 		sopp_flags |= SOCKOPT_TAIL;
17333 		sopp_tail = SSL3_MAX_TAIL_LEN;
17334 
17335 		sopp_flags |= SOCKOPT_ZCOPY;
17336 		sopp_copyopt = ZCVMUNSAFE;
17337 
17338 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
17339 	}
17340 
17341 	/* Send the options up */
17342 	if (IPCL_IS_NONSTR(connp)) {
17343 		struct sock_proto_props sopp;
17344 
17345 		sopp.sopp_flags = sopp_flags;
17346 		sopp.sopp_wroff = sopp_wroff;
17347 		sopp.sopp_maxblk = sopp_maxblk;
17348 		sopp.sopp_rxhiwat = sopp_rxhiwat;
17349 		if (sopp_flags & SOCKOPT_TAIL) {
17350 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17351 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
17352 			sopp.sopp_tail = sopp_tail;
17353 			sopp.sopp_zcopyflag = sopp_copyopt;
17354 		}
17355 		if (tcp->tcp_loopback) {
17356 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
17357 			sopp.sopp_loopback = B_TRUE;
17358 		}
17359 		(*connp->conn_upcalls->su_set_proto_props)
17360 		    (connp->conn_upper_handle, &sopp);
17361 	} else {
17362 		struct stroptions *stropt;
17363 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17364 		if (stropt_mp == NULL) {
17365 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
17366 			return;
17367 		}
17368 		DB_TYPE(stropt_mp) = M_SETOPTS;
17369 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17370 		stropt_mp->b_wptr += sizeof (struct stroptions);
17371 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
17372 		stropt->so_hiwat = sopp_rxhiwat;
17373 		stropt->so_wroff = sopp_wroff;
17374 		stropt->so_maxblk = sopp_maxblk;
17375 
17376 		if (sopp_flags & SOCKOPT_TAIL) {
17377 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17378 
17379 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
17380 			stropt->so_tail = sopp_tail;
17381 			stropt->so_copyopt = sopp_copyopt;
17382 		}
17383 
17384 		/* Send the options up */
17385 		putnext(q, stropt_mp);
17386 	}
17387 
17388 	freemsg(mp);
17389 	/*
17390 	 * Pass up any data and/or a fin that has been received.
17391 	 *
17392 	 * Adjust receive window in case it had decreased
17393 	 * (because there is data <=> tcp_rcv_list != NULL)
17394 	 * while the connection was detached. Note that
17395 	 * in case the eager was flow-controlled, w/o this
17396 	 * code, the rwnd may never open up again!
17397 	 */
17398 	if (tcp->tcp_rcv_list != NULL) {
17399 		if (IPCL_IS_NONSTR(connp)) {
17400 			mblk_t *mp;
17401 			int space_left;
17402 			int error;
17403 			boolean_t push = B_TRUE;
17404 
17405 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
17406 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
17407 			    &push) >= 0) {
17408 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17409 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17410 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17411 					tcp_xmit_ctl(NULL,
17412 					    tcp, (tcp->tcp_swnd == 0) ?
17413 					    tcp->tcp_suna : tcp->tcp_snxt,
17414 					    tcp->tcp_rnxt, TH_ACK);
17415 				}
17416 			}
17417 			while ((mp = tcp->tcp_rcv_list) != NULL) {
17418 				push = B_TRUE;
17419 				tcp->tcp_rcv_list = mp->b_next;
17420 				mp->b_next = NULL;
17421 				space_left = (*connp->conn_upcalls->su_recv)
17422 				    (connp->conn_upper_handle, mp, msgdsize(mp),
17423 				    0, &error, &push);
17424 				if (space_left < 0) {
17425 					/*
17426 					 * We should never be in middle of a
17427 					 * fallback, the squeue guarantees that.
17428 					 */
17429 					ASSERT(error != EOPNOTSUPP);
17430 				}
17431 			}
17432 			tcp->tcp_rcv_last_head = NULL;
17433 			tcp->tcp_rcv_last_tail = NULL;
17434 			tcp->tcp_rcv_cnt = 0;
17435 		} else {
17436 			/* We drain directly in case of fused tcp loopback */
17437 
17438 			if (!tcp->tcp_fused && canputnext(q)) {
17439 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17440 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17441 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17442 					tcp_xmit_ctl(NULL,
17443 					    tcp, (tcp->tcp_swnd == 0) ?
17444 					    tcp->tcp_suna : tcp->tcp_snxt,
17445 					    tcp->tcp_rnxt, TH_ACK);
17446 				}
17447 			}
17448 
17449 			(void) tcp_rcv_drain(tcp);
17450 		}
17451 
17452 		/*
17453 		 * For fused tcp loopback, back-enable peer endpoint
17454 		 * if it's currently flow-controlled.
17455 		 */
17456 		if (tcp->tcp_fused) {
17457 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17458 
17459 			ASSERT(peer_tcp != NULL);
17460 			ASSERT(peer_tcp->tcp_fused);
17461 
17462 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
17463 			if (peer_tcp->tcp_flow_stopped) {
17464 				tcp_clrqfull(peer_tcp);
17465 				TCP_STAT(tcps, tcp_fusion_backenabled);
17466 			}
17467 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17468 		}
17469 	}
17470 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17471 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17472 		tcp->tcp_ordrel_done = B_TRUE;
17473 		if (IPCL_IS_NONSTR(connp)) {
17474 			ASSERT(tcp->tcp_ordrel_mp == NULL);
17475 			(*connp->conn_upcalls->su_opctl)(
17476 			    connp->conn_upper_handle,
17477 			    SOCK_OPCTL_SHUT_RECV, 0);
17478 		} else {
17479 			mp = tcp->tcp_ordrel_mp;
17480 			tcp->tcp_ordrel_mp = NULL;
17481 			putnext(q, mp);
17482 		}
17483 	}
17484 	if (tcp->tcp_hard_binding) {
17485 		tcp->tcp_hard_binding = B_FALSE;
17486 		tcp->tcp_hard_bound = B_TRUE;
17487 	}
17488 
17489 	if (tcp->tcp_ka_enabled) {
17490 		tcp->tcp_ka_last_intrvl = 0;
17491 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17492 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17493 	}
17494 
17495 	/*
17496 	 * At this point, eager is fully established and will
17497 	 * have the following references -
17498 	 *
17499 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17500 	 * 1 reference for the squeue which will be dropped by the squeue as
17501 	 *	soon as this function returns.
17502 	 * There will be 1 additonal reference for being in classifier
17503 	 *	hash list provided something bad hasn't happened.
17504 	 */
17505 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17506 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17507 }
17508 
17509 /*
17510  * The function called through squeue to get behind listener's perimeter to
17511  * send a deffered conn_ind.
17512  */
17513 /* ARGSUSED */
17514 void
17515 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17516 {
17517 	conn_t	*connp = (conn_t *)arg;
17518 	tcp_t *listener = connp->conn_tcp;
17519 	struct T_conn_ind *conn_ind;
17520 	tcp_t *tcp;
17521 
17522 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
17523 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17524 	    conn_ind->OPT_length);
17525 
17526 	if (listener->tcp_state != TCPS_LISTEN) {
17527 		/*
17528 		 * If listener has closed, it would have caused a
17529 		 * a cleanup/blowoff to happen for the eager, so
17530 		 * we don't need to do anything more.
17531 		 */
17532 		freemsg(mp);
17533 		return;
17534 	}
17535 
17536 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
17537 }
17538 
17539 /* ARGSUSED */
17540 static int
17541 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
17542 {
17543 	tcp_t *listener, *eager;
17544 	mblk_t *opt_mp;
17545 	struct tcp_options *tcpopt;
17546 
17547 	listener = lconnp->conn_tcp;
17548 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17549 	eager = econnp->conn_tcp;
17550 	ASSERT(eager->tcp_listener != NULL);
17551 
17552 	ASSERT(eager->tcp_rq != NULL);
17553 
17554 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
17555 	if (opt_mp == NULL) {
17556 		return (-TPROTO);
17557 	}
17558 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
17559 	eager->tcp_issocket = B_TRUE;
17560 
17561 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17562 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17563 	ASSERT(econnp->conn_netstack ==
17564 	    listener->tcp_connp->conn_netstack);
17565 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
17566 
17567 	/* Put the ref for IP */
17568 	CONN_INC_REF(econnp);
17569 
17570 	/*
17571 	 * We should have minimum of 3 references on the conn
17572 	 * at this point. One each for TCP and IP and one for
17573 	 * the T_conn_ind that was sent up when the 3-way handshake
17574 	 * completed. In the normal case we would also have another
17575 	 * reference (making a total of 4) for the conn being in the
17576 	 * classifier hash list. However the eager could have received
17577 	 * an RST subsequently and tcp_closei_local could have removed
17578 	 * the eager from the classifier hash list, hence we can't
17579 	 * assert that reference.
17580 	 */
17581 	ASSERT(econnp->conn_ref >= 3);
17582 
17583 	opt_mp->b_datap->db_type = M_SETOPTS;
17584 	opt_mp->b_wptr += sizeof (struct tcp_options);
17585 
17586 	/*
17587 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17588 	 * from listener to acceptor.
17589 	 */
17590 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
17591 	tcpopt->to_flags = 0;
17592 
17593 	if (listener->tcp_bound_if != 0) {
17594 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
17595 		tcpopt->to_boundif = listener->tcp_bound_if;
17596 	}
17597 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17598 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
17599 	}
17600 
17601 	mutex_enter(&listener->tcp_eager_lock);
17602 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17603 
17604 		tcp_t *tail;
17605 		tcp_t *tcp;
17606 		mblk_t *mp1;
17607 
17608 		tcp = listener->tcp_eager_prev_q0;
17609 		/*
17610 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
17611 		 * deferred T_conn_ind queue. We need to get to the head
17612 		 * of the queue in order to send up T_conn_ind the same
17613 		 * order as how the 3WHS is completed.
17614 		 */
17615 		while (tcp != listener) {
17616 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17617 			    !tcp->tcp_kssl_pending)
17618 				break;
17619 			else
17620 				tcp = tcp->tcp_eager_prev_q0;
17621 		}
17622 		/* None of the pending eagers can be sent up now */
17623 		if (tcp == listener)
17624 			goto no_more_eagers;
17625 
17626 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17627 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17628 		/* Move from q0 to q */
17629 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17630 		listener->tcp_conn_req_cnt_q0--;
17631 		listener->tcp_conn_req_cnt_q++;
17632 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17633 		    tcp->tcp_eager_prev_q0;
17634 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17635 		    tcp->tcp_eager_next_q0;
17636 		tcp->tcp_eager_prev_q0 = NULL;
17637 		tcp->tcp_eager_next_q0 = NULL;
17638 		tcp->tcp_conn_def_q0 = B_FALSE;
17639 
17640 		/* Make sure the tcp isn't in the list of droppables */
17641 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
17642 		    tcp->tcp_eager_prev_drop_q0 == NULL);
17643 
17644 		/*
17645 		 * Insert at end of the queue because sockfs sends
17646 		 * down T_CONN_RES in chronological order. Leaving
17647 		 * the older conn indications at front of the queue
17648 		 * helps reducing search time.
17649 		 */
17650 		tail = listener->tcp_eager_last_q;
17651 		if (tail != NULL) {
17652 			tail->tcp_eager_next_q = tcp;
17653 		} else {
17654 			listener->tcp_eager_next_q = tcp;
17655 		}
17656 		listener->tcp_eager_last_q = tcp;
17657 		tcp->tcp_eager_next_q = NULL;
17658 
17659 		/* Need to get inside the listener perimeter */
17660 		CONN_INC_REF(listener->tcp_connp);
17661 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
17662 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
17663 		    SQTAG_TCP_SEND_PENDING);
17664 	}
17665 no_more_eagers:
17666 	tcp_eager_unlink(eager);
17667 	mutex_exit(&listener->tcp_eager_lock);
17668 
17669 	/*
17670 	 * At this point, the eager is detached from the listener
17671 	 * but we still have an extra refs on eager (apart from the
17672 	 * usual tcp references). The ref was placed in tcp_rput_data
17673 	 * before sending the conn_ind in tcp_send_conn_ind.
17674 	 * The ref will be dropped in tcp_accept_finish().
17675 	 */
17676 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
17677 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
17678 	return (0);
17679 }
17680 
17681 int
17682 tcp_accept(sock_lower_handle_t lproto_handle,
17683     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
17684     cred_t *cr)
17685 {
17686 	conn_t *lconnp, *econnp;
17687 	tcp_t *listener, *eager;
17688 	tcp_stack_t	*tcps;
17689 
17690 	lconnp = (conn_t *)lproto_handle;
17691 	listener = lconnp->conn_tcp;
17692 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17693 	econnp = (conn_t *)eproto_handle;
17694 	eager = econnp->conn_tcp;
17695 	ASSERT(eager->tcp_listener != NULL);
17696 	tcps = eager->tcp_tcps;
17697 
17698 	/*
17699 	 * It is OK to manipulate these fields outside the eager's squeue
17700 	 * because they will not start being used until tcp_accept_finish
17701 	 * has been called.
17702 	 */
17703 	ASSERT(lconnp->conn_upper_handle != NULL);
17704 	ASSERT(econnp->conn_upper_handle == NULL);
17705 	econnp->conn_upper_handle = sock_handle;
17706 	econnp->conn_upcalls = lconnp->conn_upcalls;
17707 	ASSERT(IPCL_IS_NONSTR(econnp));
17708 	/*
17709 	 * Create helper stream if it is a non-TPI TCP connection.
17710 	 */
17711 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
17712 		ip1dbg(("tcp_accept: create of IP helper stream"
17713 		    " failed\n"));
17714 		return (EPROTO);
17715 	}
17716 	eager->tcp_rq = econnp->conn_rq;
17717 	eager->tcp_wq = econnp->conn_wq;
17718 
17719 	ASSERT(eager->tcp_rq != NULL);
17720 
17721 	return (tcp_accept_common(lconnp, econnp, cr));
17722 }
17723 
17724 
17725 /*
17726  * This is the STREAMS entry point for T_CONN_RES coming down on
17727  * Acceptor STREAM when  sockfs listener does accept processing.
17728  * Read the block comment on top of tcp_conn_request().
17729  */
17730 void
17731 tcp_tpi_accept(queue_t *q, mblk_t *mp)
17732 {
17733 	queue_t *rq = RD(q);
17734 	struct T_conn_res *conn_res;
17735 	tcp_t *eager;
17736 	tcp_t *listener;
17737 	struct T_ok_ack *ok;
17738 	t_scalar_t PRIM_type;
17739 	conn_t *econnp;
17740 	cred_t *cr;
17741 
17742 	ASSERT(DB_TYPE(mp) == M_PROTO);
17743 
17744 	/*
17745 	 * All Solaris components should pass a db_credp
17746 	 * for this TPI message, hence we ASSERT.
17747 	 * But in case there is some other M_PROTO that looks
17748 	 * like a TPI message sent by some other kernel
17749 	 * component, we check and return an error.
17750 	 */
17751 	cr = msg_getcred(mp, NULL);
17752 	ASSERT(cr != NULL);
17753 	if (cr == NULL) {
17754 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
17755 		if (mp != NULL)
17756 			putnext(rq, mp);
17757 		return;
17758 	}
17759 	conn_res = (struct T_conn_res *)mp->b_rptr;
17760 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17761 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17762 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17763 		if (mp != NULL)
17764 			putnext(rq, mp);
17765 		return;
17766 	}
17767 	switch (conn_res->PRIM_type) {
17768 	case O_T_CONN_RES:
17769 	case T_CONN_RES:
17770 		/*
17771 		 * We pass up an err ack if allocb fails. This will
17772 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17773 		 * tcp_eager_blowoff to be called. sockfs will then call
17774 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17775 		 * we need to do the allocb up here because we have to
17776 		 * make sure rq->q_qinfo->qi_qclose still points to the
17777 		 * correct function (tcp_tpi_close_accept) in case allocb
17778 		 * fails.
17779 		 */
17780 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17781 		    &eager, conn_res->OPT_length);
17782 		PRIM_type = conn_res->PRIM_type;
17783 		mp->b_datap->db_type = M_PCPROTO;
17784 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17785 		ok = (struct T_ok_ack *)mp->b_rptr;
17786 		ok->PRIM_type = T_OK_ACK;
17787 		ok->CORRECT_prim = PRIM_type;
17788 		econnp = eager->tcp_connp;
17789 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
17790 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
17791 		eager->tcp_rq = rq;
17792 		eager->tcp_wq = q;
17793 		rq->q_ptr = econnp;
17794 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
17795 		q->q_ptr = econnp;
17796 		q->q_qinfo = &tcp_winit;
17797 		listener = eager->tcp_listener;
17798 
17799 		if (tcp_accept_common(listener->tcp_connp,
17800 		    econnp, cr) < 0) {
17801 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17802 			if (mp != NULL)
17803 				putnext(rq, mp);
17804 			return;
17805 		}
17806 
17807 		/*
17808 		 * Send the new local address also up to sockfs. There
17809 		 * should already be enough space in the mp that came
17810 		 * down from soaccept().
17811 		 */
17812 		if (eager->tcp_family == AF_INET) {
17813 			sin_t *sin;
17814 
17815 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17816 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17817 			sin = (sin_t *)mp->b_wptr;
17818 			mp->b_wptr += sizeof (sin_t);
17819 			sin->sin_family = AF_INET;
17820 			sin->sin_port = eager->tcp_lport;
17821 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17822 		} else {
17823 			sin6_t *sin6;
17824 
17825 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17826 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17827 			sin6 = (sin6_t *)mp->b_wptr;
17828 			mp->b_wptr += sizeof (sin6_t);
17829 			sin6->sin6_family = AF_INET6;
17830 			sin6->sin6_port = eager->tcp_lport;
17831 			if (eager->tcp_ipversion == IPV4_VERSION) {
17832 				sin6->sin6_flowinfo = 0;
17833 				IN6_IPADDR_TO_V4MAPPED(
17834 				    eager->tcp_ipha->ipha_src,
17835 				    &sin6->sin6_addr);
17836 			} else {
17837 				ASSERT(eager->tcp_ip6h != NULL);
17838 				sin6->sin6_flowinfo =
17839 				    eager->tcp_ip6h->ip6_vcf &
17840 				    ~IPV6_VERS_AND_FLOW_MASK;
17841 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17842 			}
17843 			sin6->sin6_scope_id = 0;
17844 			sin6->__sin6_src_id = 0;
17845 		}
17846 
17847 		putnext(rq, mp);
17848 		return;
17849 	default:
17850 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17851 		if (mp != NULL)
17852 			putnext(rq, mp);
17853 		return;
17854 	}
17855 }
17856 
17857 static int
17858 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17859 {
17860 	sin_t *sin = (sin_t *)sa;
17861 	sin6_t *sin6 = (sin6_t *)sa;
17862 
17863 	switch (tcp->tcp_family) {
17864 	case AF_INET:
17865 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17866 
17867 		if (*salenp < sizeof (sin_t))
17868 			return (EINVAL);
17869 
17870 		*sin = sin_null;
17871 		sin->sin_family = AF_INET;
17872 		if (tcp->tcp_state >= TCPS_BOUND) {
17873 			sin->sin_port = tcp->tcp_lport;
17874 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
17875 		}
17876 		*salenp = sizeof (sin_t);
17877 		break;
17878 
17879 	case AF_INET6:
17880 		if (*salenp < sizeof (sin6_t))
17881 			return (EINVAL);
17882 
17883 		*sin6 = sin6_null;
17884 		sin6->sin6_family = AF_INET6;
17885 		if (tcp->tcp_state >= TCPS_BOUND) {
17886 			sin6->sin6_port = tcp->tcp_lport;
17887 			if (tcp->tcp_ipversion == IPV4_VERSION) {
17888 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
17889 				    &sin6->sin6_addr);
17890 			} else {
17891 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
17892 			}
17893 		}
17894 		*salenp = sizeof (sin6_t);
17895 		break;
17896 	}
17897 
17898 	return (0);
17899 }
17900 
17901 static int
17902 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17903 {
17904 	sin_t *sin = (sin_t *)sa;
17905 	sin6_t *sin6 = (sin6_t *)sa;
17906 
17907 	if (tcp->tcp_state < TCPS_SYN_RCVD)
17908 		return (ENOTCONN);
17909 
17910 	switch (tcp->tcp_family) {
17911 	case AF_INET:
17912 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17913 
17914 		if (*salenp < sizeof (sin_t))
17915 			return (EINVAL);
17916 
17917 		*sin = sin_null;
17918 		sin->sin_family = AF_INET;
17919 		sin->sin_port = tcp->tcp_fport;
17920 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
17921 		    sin->sin_addr.s_addr);
17922 		*salenp = sizeof (sin_t);
17923 		break;
17924 
17925 	case AF_INET6:
17926 		if (*salenp < sizeof (sin6_t))
17927 			return (EINVAL);
17928 
17929 		*sin6 = sin6_null;
17930 		sin6->sin6_family = AF_INET6;
17931 		sin6->sin6_port = tcp->tcp_fport;
17932 		sin6->sin6_addr = tcp->tcp_remote_v6;
17933 		if (tcp->tcp_ipversion == IPV6_VERSION) {
17934 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
17935 			    ~IPV6_VERS_AND_FLOW_MASK;
17936 		}
17937 		*salenp = sizeof (sin6_t);
17938 		break;
17939 	}
17940 
17941 	return (0);
17942 }
17943 
17944 /*
17945  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
17946  */
17947 static void
17948 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
17949 {
17950 	void	*data;
17951 	mblk_t	*datamp = mp->b_cont;
17952 	tcp_t	*tcp = Q_TO_TCP(q);
17953 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
17954 
17955 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
17956 		cmdp->cb_error = EPROTO;
17957 		qreply(q, mp);
17958 		return;
17959 	}
17960 
17961 	data = datamp->b_rptr;
17962 
17963 	switch (cmdp->cb_cmd) {
17964 	case TI_GETPEERNAME:
17965 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
17966 		break;
17967 	case TI_GETMYNAME:
17968 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
17969 		break;
17970 	default:
17971 		cmdp->cb_error = EINVAL;
17972 		break;
17973 	}
17974 
17975 	qreply(q, mp);
17976 }
17977 
17978 void
17979 tcp_wput(queue_t *q, mblk_t *mp)
17980 {
17981 	conn_t	*connp = Q_TO_CONN(q);
17982 	tcp_t	*tcp;
17983 	void (*output_proc)();
17984 	t_scalar_t type;
17985 	uchar_t *rptr;
17986 	struct iocblk	*iocp;
17987 	size_t size;
17988 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17989 
17990 	ASSERT(connp->conn_ref >= 2);
17991 
17992 	switch (DB_TYPE(mp)) {
17993 	case M_DATA:
17994 		tcp = connp->conn_tcp;
17995 		ASSERT(tcp != NULL);
17996 
17997 		size = msgdsize(mp);
17998 
17999 		mutex_enter(&tcp->tcp_non_sq_lock);
18000 		tcp->tcp_squeue_bytes += size;
18001 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18002 			tcp_setqfull(tcp);
18003 		}
18004 		mutex_exit(&tcp->tcp_non_sq_lock);
18005 
18006 		CONN_INC_REF(connp);
18007 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18008 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18009 		return;
18010 
18011 	case M_CMD:
18012 		tcp_wput_cmdblk(q, mp);
18013 		return;
18014 
18015 	case M_PROTO:
18016 	case M_PCPROTO:
18017 		/*
18018 		 * if it is a snmp message, don't get behind the squeue
18019 		 */
18020 		tcp = connp->conn_tcp;
18021 		rptr = mp->b_rptr;
18022 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18023 			type = ((union T_primitives *)rptr)->type;
18024 		} else {
18025 			if (tcp->tcp_debug) {
18026 				(void) strlog(TCP_MOD_ID, 0, 1,
18027 				    SL_ERROR|SL_TRACE,
18028 				    "tcp_wput_proto, dropping one...");
18029 			}
18030 			freemsg(mp);
18031 			return;
18032 		}
18033 		if (type == T_SVR4_OPTMGMT_REQ) {
18034 			/*
18035 			 * All Solaris components should pass a db_credp
18036 			 * for this TPI message, hence we ASSERT.
18037 			 * But in case there is some other M_PROTO that looks
18038 			 * like a TPI message sent by some other kernel
18039 			 * component, we check and return an error.
18040 			 */
18041 			cred_t	*cr = msg_getcred(mp, NULL);
18042 
18043 			ASSERT(cr != NULL);
18044 			if (cr == NULL) {
18045 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18046 				return;
18047 			}
18048 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18049 			    cr)) {
18050 				/*
18051 				 * This was a SNMP request
18052 				 */
18053 				return;
18054 			} else {
18055 				output_proc = tcp_wput_proto;
18056 			}
18057 		} else {
18058 			output_proc = tcp_wput_proto;
18059 		}
18060 		break;
18061 	case M_IOCTL:
18062 		/*
18063 		 * Most ioctls can be processed right away without going via
18064 		 * squeues - process them right here. Those that do require
18065 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18066 		 * are processed by tcp_wput_ioctl().
18067 		 */
18068 		iocp = (struct iocblk *)mp->b_rptr;
18069 		tcp = connp->conn_tcp;
18070 
18071 		switch (iocp->ioc_cmd) {
18072 		case TCP_IOC_ABORT_CONN:
18073 			tcp_ioctl_abort_conn(q, mp);
18074 			return;
18075 		case TI_GETPEERNAME:
18076 		case TI_GETMYNAME:
18077 			mi_copyin(q, mp, NULL,
18078 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18079 			return;
18080 		case ND_SET:
18081 			/* nd_getset does the necessary checks */
18082 		case ND_GET:
18083 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18084 				CALL_IP_WPUT(connp, q, mp);
18085 				return;
18086 			}
18087 			qreply(q, mp);
18088 			return;
18089 		case TCP_IOC_DEFAULT_Q:
18090 			/*
18091 			 * Wants to be the default wq. Check the credentials
18092 			 * first, the rest is executed via squeue.
18093 			 */
18094 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18095 				iocp->ioc_error = EPERM;
18096 				iocp->ioc_count = 0;
18097 				mp->b_datap->db_type = M_IOCACK;
18098 				qreply(q, mp);
18099 				return;
18100 			}
18101 			output_proc = tcp_wput_ioctl;
18102 			break;
18103 		default:
18104 			output_proc = tcp_wput_ioctl;
18105 			break;
18106 		}
18107 		break;
18108 	default:
18109 		output_proc = tcp_wput_nondata;
18110 		break;
18111 	}
18112 
18113 	CONN_INC_REF(connp);
18114 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18115 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18116 }
18117 
18118 /*
18119  * Initial STREAMS write side put() procedure for sockets. It tries to
18120  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18121  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18122  * are handled by tcp_wput() as usual.
18123  *
18124  * All further messages will also be handled by tcp_wput() because we cannot
18125  * be sure that the above short cut is safe later.
18126  */
18127 static void
18128 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18129 {
18130 	conn_t			*connp = Q_TO_CONN(wq);
18131 	tcp_t			*tcp = connp->conn_tcp;
18132 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18133 
18134 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18135 	wq->q_qinfo = &tcp_winit;
18136 
18137 	ASSERT(IPCL_IS_TCP(connp));
18138 	ASSERT(TCP_IS_SOCKET(tcp));
18139 
18140 	if (DB_TYPE(mp) == M_PCPROTO &&
18141 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18142 	    car->PRIM_type == T_CAPABILITY_REQ) {
18143 		tcp_capability_req(tcp, mp);
18144 		return;
18145 	}
18146 
18147 	tcp_wput(wq, mp);
18148 }
18149 
18150 /* ARGSUSED */
18151 static void
18152 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18153 {
18154 #ifdef DEBUG
18155 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18156 #endif
18157 	freemsg(mp);
18158 }
18159 
18160 static boolean_t
18161 tcp_zcopy_check(tcp_t *tcp)
18162 {
18163 	conn_t	*connp = tcp->tcp_connp;
18164 	ire_t	*ire;
18165 	boolean_t	zc_enabled = B_FALSE;
18166 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18167 
18168 	if (do_tcpzcopy == 2)
18169 		zc_enabled = B_TRUE;
18170 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18171 	    IPCL_IS_CONNECTED(connp) &&
18172 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18173 	    connp->conn_dontroute == 0 &&
18174 	    !connp->conn_nexthop_set &&
18175 	    connp->conn_outgoing_ill == NULL &&
18176 	    do_tcpzcopy == 1) {
18177 		/*
18178 		 * the checks above  closely resemble the fast path checks
18179 		 * in tcp_send_data().
18180 		 */
18181 		mutex_enter(&connp->conn_lock);
18182 		ire = connp->conn_ire_cache;
18183 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18184 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18185 			IRE_REFHOLD(ire);
18186 			if (ire->ire_stq != NULL) {
18187 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18188 
18189 				zc_enabled = ill && (ill->ill_capabilities &
18190 				    ILL_CAPAB_ZEROCOPY) &&
18191 				    (ill->ill_zerocopy_capab->
18192 				    ill_zerocopy_flags != 0);
18193 			}
18194 			IRE_REFRELE(ire);
18195 		}
18196 		mutex_exit(&connp->conn_lock);
18197 	}
18198 	tcp->tcp_snd_zcopy_on = zc_enabled;
18199 	if (!TCP_IS_DETACHED(tcp)) {
18200 		if (zc_enabled) {
18201 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18202 			    ZCVMSAFE);
18203 			TCP_STAT(tcps, tcp_zcopy_on);
18204 		} else {
18205 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18206 			    ZCVMUNSAFE);
18207 			TCP_STAT(tcps, tcp_zcopy_off);
18208 		}
18209 	}
18210 	return (zc_enabled);
18211 }
18212 
18213 static mblk_t *
18214 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18215 {
18216 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18217 
18218 	if (do_tcpzcopy == 2)
18219 		return (bp);
18220 	else if (tcp->tcp_snd_zcopy_on) {
18221 		tcp->tcp_snd_zcopy_on = B_FALSE;
18222 		if (!TCP_IS_DETACHED(tcp)) {
18223 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18224 			    ZCVMUNSAFE);
18225 			TCP_STAT(tcps, tcp_zcopy_disable);
18226 		}
18227 	}
18228 	return (tcp_zcopy_backoff(tcp, bp, 0));
18229 }
18230 
18231 /*
18232  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18233  * the original desballoca'ed segmapped mblk.
18234  */
18235 static mblk_t *
18236 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18237 {
18238 	mblk_t *head, *tail, *nbp;
18239 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18240 
18241 	if (IS_VMLOANED_MBLK(bp)) {
18242 		TCP_STAT(tcps, tcp_zcopy_backoff);
18243 		if ((head = copyb(bp)) == NULL) {
18244 			/* fail to backoff; leave it for the next backoff */
18245 			tcp->tcp_xmit_zc_clean = B_FALSE;
18246 			return (bp);
18247 		}
18248 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18249 			if (fix_xmitlist)
18250 				tcp_zcopy_notify(tcp);
18251 			else
18252 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18253 		}
18254 		nbp = bp->b_cont;
18255 		if (fix_xmitlist) {
18256 			head->b_prev = bp->b_prev;
18257 			head->b_next = bp->b_next;
18258 			if (tcp->tcp_xmit_tail == bp)
18259 				tcp->tcp_xmit_tail = head;
18260 		}
18261 		bp->b_next = NULL;
18262 		bp->b_prev = NULL;
18263 		freeb(bp);
18264 	} else {
18265 		head = bp;
18266 		nbp = bp->b_cont;
18267 	}
18268 	tail = head;
18269 	while (nbp) {
18270 		if (IS_VMLOANED_MBLK(nbp)) {
18271 			TCP_STAT(tcps, tcp_zcopy_backoff);
18272 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18273 				tcp->tcp_xmit_zc_clean = B_FALSE;
18274 				tail->b_cont = nbp;
18275 				return (head);
18276 			}
18277 			tail = tail->b_cont;
18278 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18279 				if (fix_xmitlist)
18280 					tcp_zcopy_notify(tcp);
18281 				else
18282 					tail->b_datap->db_struioflag |=
18283 					    STRUIO_ZCNOTIFY;
18284 			}
18285 			bp = nbp;
18286 			nbp = nbp->b_cont;
18287 			if (fix_xmitlist) {
18288 				tail->b_prev = bp->b_prev;
18289 				tail->b_next = bp->b_next;
18290 				if (tcp->tcp_xmit_tail == bp)
18291 					tcp->tcp_xmit_tail = tail;
18292 			}
18293 			bp->b_next = NULL;
18294 			bp->b_prev = NULL;
18295 			freeb(bp);
18296 		} else {
18297 			tail->b_cont = nbp;
18298 			tail = nbp;
18299 			nbp = nbp->b_cont;
18300 		}
18301 	}
18302 	if (fix_xmitlist) {
18303 		tcp->tcp_xmit_last = tail;
18304 		tcp->tcp_xmit_zc_clean = B_TRUE;
18305 	}
18306 	return (head);
18307 }
18308 
18309 static void
18310 tcp_zcopy_notify(tcp_t *tcp)
18311 {
18312 	struct stdata	*stp;
18313 	conn_t *connp;
18314 
18315 	if (tcp->tcp_detached)
18316 		return;
18317 	connp = tcp->tcp_connp;
18318 	if (IPCL_IS_NONSTR(connp)) {
18319 		(*connp->conn_upcalls->su_zcopy_notify)
18320 		    (connp->conn_upper_handle);
18321 		return;
18322 	}
18323 	stp = STREAM(tcp->tcp_rq);
18324 	mutex_enter(&stp->sd_lock);
18325 	stp->sd_flag |= STZCNOTIFY;
18326 	cv_broadcast(&stp->sd_zcopy_wait);
18327 	mutex_exit(&stp->sd_lock);
18328 }
18329 
18330 static boolean_t
18331 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18332 {
18333 	ire_t	*ire;
18334 	conn_t	*connp = tcp->tcp_connp;
18335 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18336 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18337 
18338 	mutex_enter(&connp->conn_lock);
18339 	ire = connp->conn_ire_cache;
18340 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18341 
18342 	if ((ire != NULL) &&
18343 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18344 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18345 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18346 		IRE_REFHOLD(ire);
18347 		mutex_exit(&connp->conn_lock);
18348 	} else {
18349 		boolean_t cached = B_FALSE;
18350 		ts_label_t *tsl;
18351 
18352 		/* force a recheck later on */
18353 		tcp->tcp_ire_ill_check_done = B_FALSE;
18354 
18355 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18356 		connp->conn_ire_cache = NULL;
18357 		mutex_exit(&connp->conn_lock);
18358 
18359 		if (ire != NULL)
18360 			IRE_REFRELE_NOTR(ire);
18361 
18362 		tsl = crgetlabel(CONN_CRED(connp));
18363 		ire = (dst ?
18364 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18365 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18366 		    connp->conn_zoneid, tsl, ipst));
18367 
18368 		if (ire == NULL) {
18369 			TCP_STAT(tcps, tcp_ire_null);
18370 			return (B_FALSE);
18371 		}
18372 
18373 		IRE_REFHOLD_NOTR(ire);
18374 
18375 		mutex_enter(&connp->conn_lock);
18376 		if (CONN_CACHE_IRE(connp)) {
18377 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18378 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18379 				TCP_CHECK_IREINFO(tcp, ire);
18380 				connp->conn_ire_cache = ire;
18381 				cached = B_TRUE;
18382 			}
18383 			rw_exit(&ire->ire_bucket->irb_lock);
18384 		}
18385 		mutex_exit(&connp->conn_lock);
18386 
18387 		/*
18388 		 * We can continue to use the ire but since it was
18389 		 * not cached, we should drop the extra reference.
18390 		 */
18391 		if (!cached)
18392 			IRE_REFRELE_NOTR(ire);
18393 
18394 		/*
18395 		 * Rampart note: no need to select a new label here, since
18396 		 * labels are not allowed to change during the life of a TCP
18397 		 * connection.
18398 		 */
18399 	}
18400 
18401 	*irep = ire;
18402 
18403 	return (B_TRUE);
18404 }
18405 
18406 /*
18407  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18408  *
18409  * 0 = success;
18410  * 1 = failed to find ire and ill.
18411  */
18412 static boolean_t
18413 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18414 {
18415 	ipha_t		*ipha;
18416 	ipaddr_t	dst;
18417 	ire_t		*ire;
18418 	ill_t		*ill;
18419 	mblk_t		*ire_fp_mp;
18420 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18421 
18422 	if (mp != NULL)
18423 		ipha = (ipha_t *)mp->b_rptr;
18424 	else
18425 		ipha = tcp->tcp_ipha;
18426 	dst = ipha->ipha_dst;
18427 
18428 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18429 		return (B_FALSE);
18430 
18431 	if ((ire->ire_flags & RTF_MULTIRT) ||
18432 	    (ire->ire_stq == NULL) ||
18433 	    (ire->ire_nce == NULL) ||
18434 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18435 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18436 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18437 		TCP_STAT(tcps, tcp_ip_ire_send);
18438 		IRE_REFRELE(ire);
18439 		return (B_FALSE);
18440 	}
18441 
18442 	ill = ire_to_ill(ire);
18443 	ASSERT(ill != NULL);
18444 
18445 	if (!tcp->tcp_ire_ill_check_done) {
18446 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18447 		tcp->tcp_ire_ill_check_done = B_TRUE;
18448 	}
18449 
18450 	*irep = ire;
18451 	*illp = ill;
18452 
18453 	return (B_TRUE);
18454 }
18455 
18456 static void
18457 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18458 {
18459 	ipha_t		*ipha;
18460 	ipaddr_t	src;
18461 	ipaddr_t	dst;
18462 	uint32_t	cksum;
18463 	ire_t		*ire;
18464 	uint16_t	*up;
18465 	ill_t		*ill;
18466 	conn_t		*connp = tcp->tcp_connp;
18467 	uint32_t	hcksum_txflags = 0;
18468 	mblk_t		*ire_fp_mp;
18469 	uint_t		ire_fp_mp_len;
18470 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18471 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18472 	cred_t		*cr;
18473 	pid_t		cpid;
18474 
18475 	ASSERT(DB_TYPE(mp) == M_DATA);
18476 
18477 	/*
18478 	 * Here we need to handle the overloading of the cred_t for
18479 	 * both getpeerucred and TX.
18480 	 * If this is a SYN then the caller already set db_credp so
18481 	 * that getpeerucred will work. But if TX is in use we might have
18482 	 * a conn_effective_cred which is different, and we need to use that
18483 	 * cred to make TX use the correct label and label dependent route.
18484 	 */
18485 	if (is_system_labeled()) {
18486 		cr = msg_getcred(mp, &cpid);
18487 		if (cr == NULL || connp->conn_effective_cred != NULL)
18488 			mblk_setcred(mp, CONN_CRED(connp), cpid);
18489 	}
18490 
18491 	ipha = (ipha_t *)mp->b_rptr;
18492 	src = ipha->ipha_src;
18493 	dst = ipha->ipha_dst;
18494 
18495 	ASSERT(q != NULL);
18496 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
18497 
18498 	/*
18499 	 * Drop off fast path for IPv6 and also if options are present or
18500 	 * we need to resolve a TS label.
18501 	 */
18502 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18503 	    !IPCL_IS_CONNECTED(connp) ||
18504 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18505 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18506 	    !connp->conn_ulp_labeled ||
18507 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18508 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18509 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18510 		if (tcp->tcp_snd_zcopy_aware)
18511 			mp = tcp_zcopy_disable(tcp, mp);
18512 		TCP_STAT(tcps, tcp_ip_send);
18513 		CALL_IP_WPUT(connp, q, mp);
18514 		return;
18515 	}
18516 
18517 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18518 		if (tcp->tcp_snd_zcopy_aware)
18519 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18520 		CALL_IP_WPUT(connp, q, mp);
18521 		return;
18522 	}
18523 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18524 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18525 
18526 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18527 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18528 #ifndef _BIG_ENDIAN
18529 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18530 #endif
18531 
18532 	/*
18533 	 * Check to see if we need to re-enable LSO/MDT for this connection
18534 	 * because it was previously disabled due to changes in the ill;
18535 	 * note that by doing it here, this re-enabling only applies when
18536 	 * the packet is not dispatched through CALL_IP_WPUT().
18537 	 *
18538 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18539 	 * case, since that's how we ended up here.  For IPv6, we do the
18540 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18541 	 */
18542 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18543 		/*
18544 		 * Restore LSO for this connection, so that next time around
18545 		 * it is eligible to go through tcp_lsosend() path again.
18546 		 */
18547 		TCP_STAT(tcps, tcp_lso_enabled);
18548 		tcp->tcp_lso = B_TRUE;
18549 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18550 		    "interface %s\n", (void *)connp, ill->ill_name));
18551 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18552 		/*
18553 		 * Restore MDT for this connection, so that next time around
18554 		 * it is eligible to go through tcp_multisend() path again.
18555 		 */
18556 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18557 		tcp->tcp_mdt = B_TRUE;
18558 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18559 		    "interface %s\n", (void *)connp, ill->ill_name));
18560 	}
18561 
18562 	if (tcp->tcp_snd_zcopy_aware) {
18563 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18564 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18565 			mp = tcp_zcopy_disable(tcp, mp);
18566 		/*
18567 		 * we shouldn't need to reset ipha as the mp containing
18568 		 * ipha should never be a zero-copy mp.
18569 		 */
18570 	}
18571 
18572 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18573 		ASSERT(ill->ill_hcksum_capab != NULL);
18574 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18575 	}
18576 
18577 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18578 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18579 
18580 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18581 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18582 
18583 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18584 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18585 
18586 	/* Software checksum? */
18587 	if (DB_CKSUMFLAGS(mp) == 0) {
18588 		TCP_STAT(tcps, tcp_out_sw_cksum);
18589 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18590 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18591 	}
18592 
18593 	/* Calculate IP header checksum if hardware isn't capable */
18594 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18595 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18596 		    ((uint16_t *)ipha)[4]);
18597 	}
18598 
18599 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18600 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18601 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18602 
18603 	UPDATE_OB_PKT_COUNT(ire);
18604 	ire->ire_last_used_time = lbolt;
18605 
18606 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18607 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18608 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18609 	    ntohs(ipha->ipha_length));
18610 
18611 	DTRACE_PROBE4(ip4__physical__out__start,
18612 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
18613 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
18614 	    ipst->ips_ipv4firewall_physical_out,
18615 	    NULL, ill, ipha, mp, mp, 0, ipst);
18616 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18617 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
18618 
18619 	if (mp != NULL) {
18620 		if (ipst->ips_ipobs_enabled) {
18621 			zoneid_t szone;
18622 
18623 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
18624 			    ipst, ALL_ZONES);
18625 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
18626 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
18627 		}
18628 
18629 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
18630 	}
18631 
18632 	IRE_REFRELE(ire);
18633 }
18634 
18635 /*
18636  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18637  * if the receiver shrinks the window, i.e. moves the right window to the
18638  * left, the we should not send new data, but should retransmit normally the
18639  * old unacked data between suna and suna + swnd. We might has sent data
18640  * that is now outside the new window, pretend that we didn't send  it.
18641  */
18642 static void
18643 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18644 {
18645 	uint32_t	snxt = tcp->tcp_snxt;
18646 
18647 	ASSERT(shrunk_count > 0);
18648 
18649 	if (!tcp->tcp_is_wnd_shrnk) {
18650 		tcp->tcp_snxt_shrunk = snxt;
18651 		tcp->tcp_is_wnd_shrnk = B_TRUE;
18652 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
18653 		tcp->tcp_snxt_shrunk = snxt;
18654 	}
18655 
18656 	/* Pretend we didn't send the data outside the window */
18657 	snxt -= shrunk_count;
18658 
18659 	/* Reset all the values per the now shrunk window */
18660 	tcp_update_xmit_tail(tcp, snxt);
18661 	tcp->tcp_unsent += shrunk_count;
18662 
18663 	/*
18664 	 * If the SACK option is set, delete the entire list of
18665 	 * notsack'ed blocks.
18666 	 */
18667 	if (tcp->tcp_sack_info != NULL) {
18668 		if (tcp->tcp_notsack_list != NULL)
18669 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
18670 	}
18671 
18672 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18673 		/*
18674 		 * Make sure the timer is running so that we will probe a zero
18675 		 * window.
18676 		 */
18677 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18678 }
18679 
18680 
18681 /*
18682  * The TCP normal data output path.
18683  * NOTE: the logic of the fast path is duplicated from this function.
18684  */
18685 static void
18686 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18687 {
18688 	int		len;
18689 	mblk_t		*local_time;
18690 	mblk_t		*mp1;
18691 	uint32_t	snxt;
18692 	int		tail_unsent;
18693 	int		tcpstate;
18694 	int		usable = 0;
18695 	mblk_t		*xmit_tail;
18696 	queue_t		*q = tcp->tcp_wq;
18697 	int32_t		mss;
18698 	int32_t		num_sack_blk = 0;
18699 	int32_t		tcp_hdr_len;
18700 	int32_t		tcp_tcp_hdr_len;
18701 	int		mdt_thres;
18702 	int		rc;
18703 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18704 	ip_stack_t	*ipst;
18705 
18706 	tcpstate = tcp->tcp_state;
18707 	if (mp == NULL) {
18708 		/*
18709 		 * tcp_wput_data() with NULL mp should only be called when
18710 		 * there is unsent data.
18711 		 */
18712 		ASSERT(tcp->tcp_unsent > 0);
18713 		/* Really tacky... but we need this for detached closes. */
18714 		len = tcp->tcp_unsent;
18715 		goto data_null;
18716 	}
18717 
18718 #if CCS_STATS
18719 	wrw_stats.tot.count++;
18720 	wrw_stats.tot.bytes += msgdsize(mp);
18721 #endif
18722 	ASSERT(mp->b_datap->db_type == M_DATA);
18723 	/*
18724 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18725 	 * or before a connection attempt has begun.
18726 	 */
18727 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18728 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18729 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18730 #ifdef DEBUG
18731 			cmn_err(CE_WARN,
18732 			    "tcp_wput_data: data after ordrel, %s",
18733 			    tcp_display(tcp, NULL,
18734 			    DISP_ADDR_AND_PORT));
18735 #else
18736 			if (tcp->tcp_debug) {
18737 				(void) strlog(TCP_MOD_ID, 0, 1,
18738 				    SL_TRACE|SL_ERROR,
18739 				    "tcp_wput_data: data after ordrel, %s\n",
18740 				    tcp_display(tcp, NULL,
18741 				    DISP_ADDR_AND_PORT));
18742 			}
18743 #endif /* DEBUG */
18744 		}
18745 		if (tcp->tcp_snd_zcopy_aware &&
18746 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18747 			tcp_zcopy_notify(tcp);
18748 		freemsg(mp);
18749 		mutex_enter(&tcp->tcp_non_sq_lock);
18750 		if (tcp->tcp_flow_stopped &&
18751 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18752 			tcp_clrqfull(tcp);
18753 		}
18754 		mutex_exit(&tcp->tcp_non_sq_lock);
18755 		return;
18756 	}
18757 
18758 	/* Strip empties */
18759 	for (;;) {
18760 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18761 		    (uintptr_t)INT_MAX);
18762 		len = (int)(mp->b_wptr - mp->b_rptr);
18763 		if (len > 0)
18764 			break;
18765 		mp1 = mp;
18766 		mp = mp->b_cont;
18767 		freeb(mp1);
18768 		if (!mp) {
18769 			return;
18770 		}
18771 	}
18772 
18773 	/* If we are the first on the list ... */
18774 	if (tcp->tcp_xmit_head == NULL) {
18775 		tcp->tcp_xmit_head = mp;
18776 		tcp->tcp_xmit_tail = mp;
18777 		tcp->tcp_xmit_tail_unsent = len;
18778 	} else {
18779 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18780 		struct datab *dp;
18781 
18782 		mp1 = tcp->tcp_xmit_last;
18783 		if (len < tcp_tx_pull_len &&
18784 		    (dp = mp1->b_datap)->db_ref == 1 &&
18785 		    dp->db_lim - mp1->b_wptr >= len) {
18786 			ASSERT(len > 0);
18787 			ASSERT(!mp1->b_cont);
18788 			if (len == 1) {
18789 				*mp1->b_wptr++ = *mp->b_rptr;
18790 			} else {
18791 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18792 				mp1->b_wptr += len;
18793 			}
18794 			if (mp1 == tcp->tcp_xmit_tail)
18795 				tcp->tcp_xmit_tail_unsent += len;
18796 			mp1->b_cont = mp->b_cont;
18797 			if (tcp->tcp_snd_zcopy_aware &&
18798 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18799 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18800 			freeb(mp);
18801 			mp = mp1;
18802 		} else {
18803 			tcp->tcp_xmit_last->b_cont = mp;
18804 		}
18805 		len += tcp->tcp_unsent;
18806 	}
18807 
18808 	/* Tack on however many more positive length mblks we have */
18809 	if ((mp1 = mp->b_cont) != NULL) {
18810 		do {
18811 			int tlen;
18812 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18813 			    (uintptr_t)INT_MAX);
18814 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18815 			if (tlen <= 0) {
18816 				mp->b_cont = mp1->b_cont;
18817 				freeb(mp1);
18818 			} else {
18819 				len += tlen;
18820 				mp = mp1;
18821 			}
18822 		} while ((mp1 = mp->b_cont) != NULL);
18823 	}
18824 	tcp->tcp_xmit_last = mp;
18825 	tcp->tcp_unsent = len;
18826 
18827 	if (urgent)
18828 		usable = 1;
18829 
18830 data_null:
18831 	snxt = tcp->tcp_snxt;
18832 	xmit_tail = tcp->tcp_xmit_tail;
18833 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18834 
18835 	/*
18836 	 * Note that tcp_mss has been adjusted to take into account the
18837 	 * timestamp option if applicable.  Because SACK options do not
18838 	 * appear in every TCP segments and they are of variable lengths,
18839 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18840 	 * the actual segment length when we need to send a segment which
18841 	 * includes SACK options.
18842 	 */
18843 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18844 		int32_t	opt_len;
18845 
18846 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18847 		    tcp->tcp_num_sack_blk);
18848 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18849 		    2 + TCPOPT_HEADER_LEN;
18850 		mss = tcp->tcp_mss - opt_len;
18851 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18852 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18853 	} else {
18854 		mss = tcp->tcp_mss;
18855 		tcp_hdr_len = tcp->tcp_hdr_len;
18856 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18857 	}
18858 
18859 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18860 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18861 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18862 	}
18863 	if (tcpstate == TCPS_SYN_RCVD) {
18864 		/*
18865 		 * The three-way connection establishment handshake is not
18866 		 * complete yet. We want to queue the data for transmission
18867 		 * after entering ESTABLISHED state (RFC793). A jump to
18868 		 * "done" label effectively leaves data on the queue.
18869 		 */
18870 		goto done;
18871 	} else {
18872 		int usable_r;
18873 
18874 		/*
18875 		 * In the special case when cwnd is zero, which can only
18876 		 * happen if the connection is ECN capable, return now.
18877 		 * New segments is sent using tcp_timer().  The timer
18878 		 * is set in tcp_rput_data().
18879 		 */
18880 		if (tcp->tcp_cwnd == 0) {
18881 			/*
18882 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18883 			 * finished.
18884 			 */
18885 			ASSERT(tcp->tcp_ecn_ok ||
18886 			    tcp->tcp_state < TCPS_ESTABLISHED);
18887 			return;
18888 		}
18889 
18890 		/* NOTE: trouble if xmitting while SYN not acked? */
18891 		usable_r = snxt - tcp->tcp_suna;
18892 		usable_r = tcp->tcp_swnd - usable_r;
18893 
18894 		/*
18895 		 * Check if the receiver has shrunk the window.  If
18896 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18897 		 * cannot be set as there is unsent data, so FIN cannot
18898 		 * be sent out.  Otherwise, we need to take into account
18899 		 * of FIN as it consumes an "invisible" sequence number.
18900 		 */
18901 		ASSERT(tcp->tcp_fin_sent == 0);
18902 		if (usable_r < 0) {
18903 			/*
18904 			 * The receiver has shrunk the window and we have sent
18905 			 * -usable_r date beyond the window, re-adjust.
18906 			 *
18907 			 * If TCP window scaling is enabled, there can be
18908 			 * round down error as the advertised receive window
18909 			 * is actually right shifted n bits.  This means that
18910 			 * the lower n bits info is wiped out.  It will look
18911 			 * like the window is shrunk.  Do a check here to
18912 			 * see if the shrunk amount is actually within the
18913 			 * error in window calculation.  If it is, just
18914 			 * return.  Note that this check is inside the
18915 			 * shrunk window check.  This makes sure that even
18916 			 * though tcp_process_shrunk_swnd() is not called,
18917 			 * we will stop further processing.
18918 			 */
18919 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18920 				tcp_process_shrunk_swnd(tcp, -usable_r);
18921 			}
18922 			return;
18923 		}
18924 
18925 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18926 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18927 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18928 
18929 		/* usable = MIN(usable, unsent) */
18930 		if (usable_r > len)
18931 			usable_r = len;
18932 
18933 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18934 		if (usable_r > 0) {
18935 			usable = usable_r;
18936 		} else {
18937 			/* Bypass all other unnecessary processing. */
18938 			goto done;
18939 		}
18940 	}
18941 
18942 	local_time = (mblk_t *)lbolt;
18943 
18944 	/*
18945 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18946 	 * BSD.  This is more in line with the true intent of Nagle.
18947 	 *
18948 	 * The conditions are:
18949 	 * 1. The amount of unsent data (or amount of data which can be
18950 	 *    sent, whichever is smaller) is less than Nagle limit.
18951 	 * 2. The last sent size is also less than Nagle limit.
18952 	 * 3. There is unack'ed data.
18953 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18954 	 *    Nagle algorithm.  This reduces the probability that urgent
18955 	 *    bytes get "merged" together.
18956 	 * 5. The app has not closed the connection.  This eliminates the
18957 	 *    wait time of the receiving side waiting for the last piece of
18958 	 *    (small) data.
18959 	 *
18960 	 * If all are satisified, exit without sending anything.  Note
18961 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18962 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18963 	 * 4095).
18964 	 */
18965 	if (usable < (int)tcp->tcp_naglim &&
18966 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18967 	    snxt != tcp->tcp_suna &&
18968 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18969 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18970 		goto done;
18971 	}
18972 
18973 	/*
18974 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
18975 	 * is set, then we have to force TCP not to send partial segment
18976 	 * (smaller than MSS bytes). We are calculating the usable now
18977 	 * based on full mss and will save the rest of remaining data for
18978 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
18979 	 * something to do zero window probe.
18980 	 */
18981 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
18982 		if (usable < mss)
18983 			goto done;
18984 		usable = (usable / mss) * mss;
18985 	}
18986 
18987 	/* Update the latest receive window size in TCP header. */
18988 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18989 	    tcp->tcp_tcph->th_win);
18990 
18991 	/*
18992 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
18993 	 *
18994 	 * 1. Simple TCP/IP{v4,v6} (no options).
18995 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18996 	 * 3. If the TCP connection is in ESTABLISHED state.
18997 	 * 4. The TCP is not detached.
18998 	 *
18999 	 * If any of the above conditions have changed during the
19000 	 * connection, stop using LSO/MDT and restore the stream head
19001 	 * parameters accordingly.
19002 	 */
19003 	ipst = tcps->tcps_netstack->netstack_ip;
19004 
19005 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19006 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19007 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19008 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19009 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19010 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19011 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19012 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19013 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19014 		if (tcp->tcp_lso) {
19015 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19016 			tcp->tcp_lso = B_FALSE;
19017 		} else {
19018 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19019 			tcp->tcp_mdt = B_FALSE;
19020 		}
19021 
19022 		/* Anything other than detached is considered pathological */
19023 		if (!TCP_IS_DETACHED(tcp)) {
19024 			if (tcp->tcp_lso)
19025 				TCP_STAT(tcps, tcp_lso_disabled);
19026 			else
19027 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19028 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19029 		}
19030 	}
19031 
19032 	/* Use MDT if sendable amount is greater than the threshold */
19033 	if (tcp->tcp_mdt &&
19034 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19035 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19036 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19037 	    (tcp->tcp_valid_bits == 0 ||
19038 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19039 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19040 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19041 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19042 		    local_time, mdt_thres);
19043 	} else {
19044 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19045 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19046 		    local_time, INT_MAX);
19047 	}
19048 
19049 	/* Pretend that all we were trying to send really got sent */
19050 	if (rc < 0 && tail_unsent < 0) {
19051 		do {
19052 			xmit_tail = xmit_tail->b_cont;
19053 			xmit_tail->b_prev = local_time;
19054 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19055 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19056 			tail_unsent += (int)(xmit_tail->b_wptr -
19057 			    xmit_tail->b_rptr);
19058 		} while (tail_unsent < 0);
19059 	}
19060 done:;
19061 	tcp->tcp_xmit_tail = xmit_tail;
19062 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19063 	len = tcp->tcp_snxt - snxt;
19064 	if (len) {
19065 		/*
19066 		 * If new data was sent, need to update the notsack
19067 		 * list, which is, afterall, data blocks that have
19068 		 * not been sack'ed by the receiver.  New data is
19069 		 * not sack'ed.
19070 		 */
19071 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19072 			/* len is a negative value. */
19073 			tcp->tcp_pipe -= len;
19074 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19075 			    tcp->tcp_snxt, snxt,
19076 			    &(tcp->tcp_num_notsack_blk),
19077 			    &(tcp->tcp_cnt_notsack_list));
19078 		}
19079 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19080 		tcp->tcp_rack = tcp->tcp_rnxt;
19081 		tcp->tcp_rack_cnt = 0;
19082 		if ((snxt + len) == tcp->tcp_suna) {
19083 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19084 		}
19085 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19086 		/*
19087 		 * Didn't send anything. Make sure the timer is running
19088 		 * so that we will probe a zero window.
19089 		 */
19090 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19091 	}
19092 	/* Note that len is the amount we just sent but with a negative sign */
19093 	tcp->tcp_unsent += len;
19094 	mutex_enter(&tcp->tcp_non_sq_lock);
19095 	if (tcp->tcp_flow_stopped) {
19096 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19097 			tcp_clrqfull(tcp);
19098 		}
19099 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19100 		tcp_setqfull(tcp);
19101 	}
19102 	mutex_exit(&tcp->tcp_non_sq_lock);
19103 }
19104 
19105 /*
19106  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19107  * outgoing TCP header with the template header, as well as other
19108  * options such as time-stamp, ECN and/or SACK.
19109  */
19110 static void
19111 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19112 {
19113 	tcph_t *tcp_tmpl, *tcp_h;
19114 	uint32_t *dst, *src;
19115 	int hdrlen;
19116 
19117 	ASSERT(OK_32PTR(rptr));
19118 
19119 	/* Template header */
19120 	tcp_tmpl = tcp->tcp_tcph;
19121 
19122 	/* Header of outgoing packet */
19123 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19124 
19125 	/* dst and src are opaque 32-bit fields, used for copying */
19126 	dst = (uint32_t *)rptr;
19127 	src = (uint32_t *)tcp->tcp_iphc;
19128 	hdrlen = tcp->tcp_hdr_len;
19129 
19130 	/* Fill time-stamp option if needed */
19131 	if (tcp->tcp_snd_ts_ok) {
19132 		U32_TO_BE32((uint32_t)now,
19133 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19134 		U32_TO_BE32(tcp->tcp_ts_recent,
19135 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19136 	} else {
19137 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19138 	}
19139 
19140 	/*
19141 	 * Copy the template header; is this really more efficient than
19142 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19143 	 * but perhaps not for other scenarios.
19144 	 */
19145 	dst[0] = src[0];
19146 	dst[1] = src[1];
19147 	dst[2] = src[2];
19148 	dst[3] = src[3];
19149 	dst[4] = src[4];
19150 	dst[5] = src[5];
19151 	dst[6] = src[6];
19152 	dst[7] = src[7];
19153 	dst[8] = src[8];
19154 	dst[9] = src[9];
19155 	if (hdrlen -= 40) {
19156 		hdrlen >>= 2;
19157 		dst += 10;
19158 		src += 10;
19159 		do {
19160 			*dst++ = *src++;
19161 		} while (--hdrlen);
19162 	}
19163 
19164 	/*
19165 	 * Set the ECN info in the TCP header if it is not a zero
19166 	 * window probe.  Zero window probe is only sent in
19167 	 * tcp_wput_data() and tcp_timer().
19168 	 */
19169 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19170 		SET_ECT(tcp, rptr);
19171 
19172 		if (tcp->tcp_ecn_echo_on)
19173 			tcp_h->th_flags[0] |= TH_ECE;
19174 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19175 			tcp_h->th_flags[0] |= TH_CWR;
19176 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19177 		}
19178 	}
19179 
19180 	/* Fill in SACK options */
19181 	if (num_sack_blk > 0) {
19182 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19183 		sack_blk_t *tmp;
19184 		int32_t	i;
19185 
19186 		wptr[0] = TCPOPT_NOP;
19187 		wptr[1] = TCPOPT_NOP;
19188 		wptr[2] = TCPOPT_SACK;
19189 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19190 		    sizeof (sack_blk_t);
19191 		wptr += TCPOPT_REAL_SACK_LEN;
19192 
19193 		tmp = tcp->tcp_sack_list;
19194 		for (i = 0; i < num_sack_blk; i++) {
19195 			U32_TO_BE32(tmp[i].begin, wptr);
19196 			wptr += sizeof (tcp_seq);
19197 			U32_TO_BE32(tmp[i].end, wptr);
19198 			wptr += sizeof (tcp_seq);
19199 		}
19200 		tcp_h->th_offset_and_rsrvd[0] +=
19201 		    ((num_sack_blk * 2 + 1) << 4);
19202 	}
19203 }
19204 
19205 /*
19206  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19207  * the destination address and SAP attribute, and if necessary, the
19208  * hardware checksum offload attribute to a Multidata message.
19209  */
19210 static int
19211 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19212     const uint32_t start, const uint32_t stuff, const uint32_t end,
19213     const uint32_t flags, tcp_stack_t *tcps)
19214 {
19215 	/* Add global destination address & SAP attribute */
19216 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19217 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19218 		    "destination address+SAP\n"));
19219 
19220 		if (dlmp != NULL)
19221 			TCP_STAT(tcps, tcp_mdt_allocfail);
19222 		return (-1);
19223 	}
19224 
19225 	/* Add global hwcksum attribute */
19226 	if (hwcksum &&
19227 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19228 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19229 		    "checksum attribute\n"));
19230 
19231 		TCP_STAT(tcps, tcp_mdt_allocfail);
19232 		return (-1);
19233 	}
19234 
19235 	return (0);
19236 }
19237 
19238 /*
19239  * Smaller and private version of pdescinfo_t used specifically for TCP,
19240  * which allows for only two payload spans per packet.
19241  */
19242 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19243 
19244 /*
19245  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19246  * scheme, and returns one the following:
19247  *
19248  * -1 = failed allocation.
19249  *  0 = success; burst count reached, or usable send window is too small,
19250  *      and that we'd rather wait until later before sending again.
19251  */
19252 static int
19253 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19254     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19255     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19256     const int mdt_thres)
19257 {
19258 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19259 	multidata_t	*mmd;
19260 	uint_t		obsegs, obbytes, hdr_frag_sz;
19261 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19262 	int		num_burst_seg, max_pld;
19263 	pdesc_t		*pkt;
19264 	tcp_pdescinfo_t	tcp_pkt_info;
19265 	pdescinfo_t	*pkt_info;
19266 	int		pbuf_idx, pbuf_idx_nxt;
19267 	int		seg_len, len, spill, af;
19268 	boolean_t	add_buffer, zcopy, clusterwide;
19269 	boolean_t	rconfirm = B_FALSE;
19270 	boolean_t	done = B_FALSE;
19271 	uint32_t	cksum;
19272 	uint32_t	hwcksum_flags;
19273 	ire_t		*ire = NULL;
19274 	ill_t		*ill;
19275 	ipha_t		*ipha;
19276 	ip6_t		*ip6h;
19277 	ipaddr_t	src, dst;
19278 	ill_zerocopy_capab_t *zc_cap = NULL;
19279 	uint16_t	*up;
19280 	int		err;
19281 	conn_t		*connp;
19282 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19283 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19284 	int		usable_mmd, tail_unsent_mmd;
19285 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19286 	mblk_t		*xmit_tail_mmd;
19287 	netstackid_t	stack_id;
19288 
19289 #ifdef	_BIG_ENDIAN
19290 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19291 #else
19292 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19293 #endif
19294 
19295 #define	PREP_NEW_MULTIDATA() {			\
19296 	mmd = NULL;				\
19297 	md_mp = md_hbuf = NULL;			\
19298 	cur_hdr_off = 0;			\
19299 	max_pld = tcp->tcp_mdt_max_pld;		\
19300 	pbuf_idx = pbuf_idx_nxt = -1;		\
19301 	add_buffer = B_TRUE;			\
19302 	zcopy = B_FALSE;			\
19303 }
19304 
19305 #define	PREP_NEW_PBUF() {			\
19306 	md_pbuf = md_pbuf_nxt = NULL;		\
19307 	pbuf_idx = pbuf_idx_nxt = -1;		\
19308 	cur_pld_off = 0;			\
19309 	first_snxt = *snxt;			\
19310 	ASSERT(*tail_unsent > 0);		\
19311 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19312 }
19313 
19314 	ASSERT(mdt_thres >= mss);
19315 	ASSERT(*usable > 0 && *usable > mdt_thres);
19316 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19317 	ASSERT(!TCP_IS_DETACHED(tcp));
19318 	ASSERT(tcp->tcp_valid_bits == 0 ||
19319 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19320 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19321 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19322 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19323 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19324 
19325 	connp = tcp->tcp_connp;
19326 	ASSERT(connp != NULL);
19327 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19328 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19329 
19330 	stack_id = connp->conn_netstack->netstack_stackid;
19331 
19332 	usable_mmd = tail_unsent_mmd = 0;
19333 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
19334 	xmit_tail_mmd = NULL;
19335 	/*
19336 	 * Note that tcp will only declare at most 2 payload spans per
19337 	 * packet, which is much lower than the maximum allowable number
19338 	 * of packet spans per Multidata.  For this reason, we use the
19339 	 * privately declared and smaller descriptor info structure, in
19340 	 * order to save some stack space.
19341 	 */
19342 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19343 
19344 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19345 	if (af == AF_INET) {
19346 		dst = tcp->tcp_ipha->ipha_dst;
19347 		src = tcp->tcp_ipha->ipha_src;
19348 		ASSERT(!CLASSD(dst));
19349 	}
19350 	ASSERT(af == AF_INET ||
19351 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19352 
19353 	obsegs = obbytes = 0;
19354 	num_burst_seg = tcp->tcp_snd_burst;
19355 	md_mp_head = NULL;
19356 	PREP_NEW_MULTIDATA();
19357 
19358 	/*
19359 	 * Before we go on further, make sure there is an IRE that we can
19360 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19361 	 * in proceeding any further, and we should just hand everything
19362 	 * off to the legacy path.
19363 	 */
19364 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19365 		goto legacy_send_no_md;
19366 
19367 	ASSERT(ire != NULL);
19368 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19369 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19370 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19371 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19372 	/*
19373 	 * If we do support loopback for MDT (which requires modifications
19374 	 * to the receiving paths), the following assertions should go away,
19375 	 * and we would be sending the Multidata to loopback conn later on.
19376 	 */
19377 	ASSERT(!IRE_IS_LOCAL(ire));
19378 	ASSERT(ire->ire_stq != NULL);
19379 
19380 	ill = ire_to_ill(ire);
19381 	ASSERT(ill != NULL);
19382 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19383 
19384 	if (!tcp->tcp_ire_ill_check_done) {
19385 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19386 		tcp->tcp_ire_ill_check_done = B_TRUE;
19387 	}
19388 
19389 	/*
19390 	 * If the underlying interface conditions have changed, or if the
19391 	 * new interface does not support MDT, go back to legacy path.
19392 	 */
19393 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19394 		/* don't go through this path anymore for this connection */
19395 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19396 		tcp->tcp_mdt = B_FALSE;
19397 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19398 		    "interface %s\n", (void *)connp, ill->ill_name));
19399 		/* IRE will be released prior to returning */
19400 		goto legacy_send_no_md;
19401 	}
19402 
19403 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19404 		zc_cap = ill->ill_zerocopy_capab;
19405 
19406 	/*
19407 	 * Check if we can take tcp fast-path. Note that "incomplete"
19408 	 * ire's (where the link-layer for next hop is not resolved
19409 	 * or where the fast-path header in nce_fp_mp is not available
19410 	 * yet) are sent down the legacy (slow) path.
19411 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19412 	 */
19413 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19414 		/* IRE will be released prior to returning */
19415 		goto legacy_send_no_md;
19416 	}
19417 
19418 	/* go to legacy path if interface doesn't support zerocopy */
19419 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19420 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19421 		/* IRE will be released prior to returning */
19422 		goto legacy_send_no_md;
19423 	}
19424 
19425 	/* does the interface support hardware checksum offload? */
19426 	hwcksum_flags = 0;
19427 	if (ILL_HCKSUM_CAPABLE(ill) &&
19428 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19429 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19430 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19431 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19432 		    HCKSUM_IPHDRCKSUM)
19433 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19434 
19435 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19436 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19437 			hwcksum_flags |= HCK_FULLCKSUM;
19438 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19439 		    HCKSUM_INET_PARTIAL)
19440 			hwcksum_flags |= HCK_PARTIALCKSUM;
19441 	}
19442 
19443 	/*
19444 	 * Each header fragment consists of the leading extra space,
19445 	 * followed by the TCP/IP header, and the trailing extra space.
19446 	 * We make sure that each header fragment begins on a 32-bit
19447 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19448 	 * aligned in tcp_mdt_update).
19449 	 */
19450 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19451 	    tcp->tcp_mdt_hdr_tail), 4);
19452 
19453 	/* are we starting from the beginning of data block? */
19454 	if (*tail_unsent == 0) {
19455 		*xmit_tail = (*xmit_tail)->b_cont;
19456 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19457 		*tail_unsent = (int)MBLKL(*xmit_tail);
19458 	}
19459 
19460 	/*
19461 	 * Here we create one or more Multidata messages, each made up of
19462 	 * one header buffer and up to N payload buffers.  This entire
19463 	 * operation is done within two loops:
19464 	 *
19465 	 * The outer loop mostly deals with creating the Multidata message,
19466 	 * as well as the header buffer that gets added to it.  It also
19467 	 * links the Multidata messages together such that all of them can
19468 	 * be sent down to the lower layer in a single putnext call; this
19469 	 * linking behavior depends on the tcp_mdt_chain tunable.
19470 	 *
19471 	 * The inner loop takes an existing Multidata message, and adds
19472 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19473 	 * packetizes those buffers by filling up the corresponding header
19474 	 * buffer fragments with the proper IP and TCP headers, and by
19475 	 * describing the layout of each packet in the packet descriptors
19476 	 * that get added to the Multidata.
19477 	 */
19478 	do {
19479 		/*
19480 		 * If usable send window is too small, or data blocks in
19481 		 * transmit list are smaller than our threshold (i.e. app
19482 		 * performs large writes followed by small ones), we hand
19483 		 * off the control over to the legacy path.  Note that we'll
19484 		 * get back the control once it encounters a large block.
19485 		 */
19486 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19487 		    (*xmit_tail)->b_cont != NULL &&
19488 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19489 			/* send down what we've got so far */
19490 			if (md_mp_head != NULL) {
19491 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19492 				    obsegs, obbytes, &rconfirm);
19493 			}
19494 			/*
19495 			 * Pass control over to tcp_send(), but tell it to
19496 			 * return to us once a large-size transmission is
19497 			 * possible.
19498 			 */
19499 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19500 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19501 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19502 			    tail_unsent, xmit_tail, local_time,
19503 			    mdt_thres)) <= 0) {
19504 				/* burst count reached, or alloc failed */
19505 				IRE_REFRELE(ire);
19506 				return (err);
19507 			}
19508 
19509 			/* tcp_send() may have sent everything, so check */
19510 			if (*usable <= 0) {
19511 				IRE_REFRELE(ire);
19512 				return (0);
19513 			}
19514 
19515 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19516 			/*
19517 			 * We may have delivered the Multidata, so make sure
19518 			 * to re-initialize before the next round.
19519 			 */
19520 			md_mp_head = NULL;
19521 			obsegs = obbytes = 0;
19522 			num_burst_seg = tcp->tcp_snd_burst;
19523 			PREP_NEW_MULTIDATA();
19524 
19525 			/* are we starting from the beginning of data block? */
19526 			if (*tail_unsent == 0) {
19527 				*xmit_tail = (*xmit_tail)->b_cont;
19528 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19529 				    (uintptr_t)INT_MAX);
19530 				*tail_unsent = (int)MBLKL(*xmit_tail);
19531 			}
19532 		}
19533 		/*
19534 		 * Record current values for parameters we may need to pass
19535 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
19536 		 * each iteration of the outer loop (each multidata message
19537 		 * creation). If we have a failure in the inner loop, we send
19538 		 * any complete multidata messages we have before reverting
19539 		 * to using the traditional non-md path.
19540 		 */
19541 		snxt_mmd = *snxt;
19542 		usable_mmd = *usable;
19543 		xmit_tail_mmd = *xmit_tail;
19544 		tail_unsent_mmd = *tail_unsent;
19545 		obsegs_mmd = obsegs;
19546 		obbytes_mmd = obbytes;
19547 
19548 		/*
19549 		 * max_pld limits the number of mblks in tcp's transmit
19550 		 * queue that can be added to a Multidata message.  Once
19551 		 * this counter reaches zero, no more additional mblks
19552 		 * can be added to it.  What happens afterwards depends
19553 		 * on whether or not we are set to chain the Multidata
19554 		 * messages.  If we are to link them together, reset
19555 		 * max_pld to its original value (tcp_mdt_max_pld) and
19556 		 * prepare to create a new Multidata message which will
19557 		 * get linked to md_mp_head.  Else, leave it alone and
19558 		 * let the inner loop break on its own.
19559 		 */
19560 		if (tcp_mdt_chain && max_pld == 0)
19561 			PREP_NEW_MULTIDATA();
19562 
19563 		/* adding a payload buffer; re-initialize values */
19564 		if (add_buffer)
19565 			PREP_NEW_PBUF();
19566 
19567 		/*
19568 		 * If we don't have a Multidata, either because we just
19569 		 * (re)entered this outer loop, or after we branched off
19570 		 * to tcp_send above, setup the Multidata and header
19571 		 * buffer to be used.
19572 		 */
19573 		if (md_mp == NULL) {
19574 			int md_hbuflen;
19575 			uint32_t start, stuff;
19576 
19577 			/*
19578 			 * Calculate Multidata header buffer size large enough
19579 			 * to hold all of the headers that can possibly be
19580 			 * sent at this moment.  We'd rather over-estimate
19581 			 * the size than running out of space; this is okay
19582 			 * since this buffer is small anyway.
19583 			 */
19584 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19585 
19586 			/*
19587 			 * Start and stuff offset for partial hardware
19588 			 * checksum offload; these are currently for IPv4.
19589 			 * For full checksum offload, they are set to zero.
19590 			 */
19591 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19592 				if (af == AF_INET) {
19593 					start = IP_SIMPLE_HDR_LENGTH;
19594 					stuff = IP_SIMPLE_HDR_LENGTH +
19595 					    TCP_CHECKSUM_OFFSET;
19596 				} else {
19597 					start = IPV6_HDR_LEN;
19598 					stuff = IPV6_HDR_LEN +
19599 					    TCP_CHECKSUM_OFFSET;
19600 				}
19601 			} else {
19602 				start = stuff = 0;
19603 			}
19604 
19605 			/*
19606 			 * Create the header buffer, Multidata, as well as
19607 			 * any necessary attributes (destination address,
19608 			 * SAP and hardware checksum offload) that should
19609 			 * be associated with the Multidata message.
19610 			 */
19611 			ASSERT(cur_hdr_off == 0);
19612 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19613 			    ((md_hbuf->b_wptr += md_hbuflen),
19614 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19615 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19616 			    /* fastpath mblk */
19617 			    ire->ire_nce->nce_res_mp,
19618 			    /* hardware checksum enabled */
19619 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19620 			    /* hardware checksum offsets */
19621 			    start, stuff, 0,
19622 			    /* hardware checksum flag */
19623 			    hwcksum_flags, tcps) != 0)) {
19624 legacy_send:
19625 				/*
19626 				 * We arrive here from a failure within the
19627 				 * inner (packetizer) loop or we fail one of
19628 				 * the conditionals above. We restore the
19629 				 * previously checkpointed values for:
19630 				 *    xmit_tail
19631 				 *    usable
19632 				 *    tail_unsent
19633 				 *    snxt
19634 				 *    obbytes
19635 				 *    obsegs
19636 				 * We should then be able to dispatch any
19637 				 * complete multidata before reverting to the
19638 				 * traditional path with consistent parameters
19639 				 * (the inner loop updates these as it
19640 				 * iterates).
19641 				 */
19642 				*xmit_tail = xmit_tail_mmd;
19643 				*usable = usable_mmd;
19644 				*tail_unsent = tail_unsent_mmd;
19645 				*snxt = snxt_mmd;
19646 				obbytes = obbytes_mmd;
19647 				obsegs = obsegs_mmd;
19648 				if (md_mp != NULL) {
19649 					/* Unlink message from the chain */
19650 					if (md_mp_head != NULL) {
19651 						err = (intptr_t)rmvb(md_mp_head,
19652 						    md_mp);
19653 						/*
19654 						 * We can't assert that rmvb
19655 						 * did not return -1, since we
19656 						 * may get here before linkb
19657 						 * happens.  We do, however,
19658 						 * check if we just removed the
19659 						 * only element in the list.
19660 						 */
19661 						if (err == 0)
19662 							md_mp_head = NULL;
19663 					}
19664 					/* md_hbuf gets freed automatically */
19665 					TCP_STAT(tcps, tcp_mdt_discarded);
19666 					freeb(md_mp);
19667 				} else {
19668 					/* Either allocb or mmd_alloc failed */
19669 					TCP_STAT(tcps, tcp_mdt_allocfail);
19670 					if (md_hbuf != NULL)
19671 						freeb(md_hbuf);
19672 				}
19673 
19674 				/* send down what we've got so far */
19675 				if (md_mp_head != NULL) {
19676 					tcp_multisend_data(tcp, ire, ill,
19677 					    md_mp_head, obsegs, obbytes,
19678 					    &rconfirm);
19679 				}
19680 legacy_send_no_md:
19681 				if (ire != NULL)
19682 					IRE_REFRELE(ire);
19683 				/*
19684 				 * Too bad; let the legacy path handle this.
19685 				 * We specify INT_MAX for the threshold, since
19686 				 * we gave up with the Multidata processings
19687 				 * and let the old path have it all.
19688 				 */
19689 				TCP_STAT(tcps, tcp_mdt_legacy_all);
19690 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19691 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19692 				    snxt, tail_unsent, xmit_tail, local_time,
19693 				    INT_MAX));
19694 			}
19695 
19696 			/* link to any existing ones, if applicable */
19697 			TCP_STAT(tcps, tcp_mdt_allocd);
19698 			if (md_mp_head == NULL) {
19699 				md_mp_head = md_mp;
19700 			} else if (tcp_mdt_chain) {
19701 				TCP_STAT(tcps, tcp_mdt_linked);
19702 				linkb(md_mp_head, md_mp);
19703 			}
19704 		}
19705 
19706 		ASSERT(md_mp_head != NULL);
19707 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19708 		ASSERT(md_mp != NULL && mmd != NULL);
19709 		ASSERT(md_hbuf != NULL);
19710 
19711 		/*
19712 		 * Packetize the transmittable portion of the data block;
19713 		 * each data block is essentially added to the Multidata
19714 		 * as a payload buffer.  We also deal with adding more
19715 		 * than one payload buffers, which happens when the remaining
19716 		 * packetized portion of the current payload buffer is less
19717 		 * than MSS, while the next data block in transmit queue
19718 		 * has enough data to make up for one.  This "spillover"
19719 		 * case essentially creates a split-packet, where portions
19720 		 * of the packet's payload fragments may span across two
19721 		 * virtually discontiguous address blocks.
19722 		 */
19723 		seg_len = mss;
19724 		do {
19725 			len = seg_len;
19726 
19727 			/* one must remain NULL for DTRACE_IP_FASTPATH */
19728 			ipha = NULL;
19729 			ip6h = NULL;
19730 
19731 			ASSERT(len > 0);
19732 			ASSERT(max_pld >= 0);
19733 			ASSERT(!add_buffer || cur_pld_off == 0);
19734 
19735 			/*
19736 			 * First time around for this payload buffer; note
19737 			 * in the case of a spillover, the following has
19738 			 * been done prior to adding the split-packet
19739 			 * descriptor to Multidata, and we don't want to
19740 			 * repeat the process.
19741 			 */
19742 			if (add_buffer) {
19743 				ASSERT(mmd != NULL);
19744 				ASSERT(md_pbuf == NULL);
19745 				ASSERT(md_pbuf_nxt == NULL);
19746 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19747 
19748 				/*
19749 				 * Have we reached the limit?  We'd get to
19750 				 * this case when we're not chaining the
19751 				 * Multidata messages together, and since
19752 				 * we're done, terminate this loop.
19753 				 */
19754 				if (max_pld == 0)
19755 					break; /* done */
19756 
19757 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19758 					TCP_STAT(tcps, tcp_mdt_allocfail);
19759 					goto legacy_send; /* out_of_mem */
19760 				}
19761 
19762 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19763 				    zc_cap != NULL) {
19764 					if (!ip_md_zcopy_attr(mmd, NULL,
19765 					    zc_cap->ill_zerocopy_flags)) {
19766 						freeb(md_pbuf);
19767 						TCP_STAT(tcps,
19768 						    tcp_mdt_allocfail);
19769 						/* out_of_mem */
19770 						goto legacy_send;
19771 					}
19772 					zcopy = B_TRUE;
19773 				}
19774 
19775 				md_pbuf->b_rptr += base_pld_off;
19776 
19777 				/*
19778 				 * Add a payload buffer to the Multidata; this
19779 				 * operation must not fail, or otherwise our
19780 				 * logic in this routine is broken.  There
19781 				 * is no memory allocation done by the
19782 				 * routine, so any returned failure simply
19783 				 * tells us that we've done something wrong.
19784 				 *
19785 				 * A failure tells us that either we're adding
19786 				 * the same payload buffer more than once, or
19787 				 * we're trying to add more buffers than
19788 				 * allowed (max_pld calculation is wrong).
19789 				 * None of the above cases should happen, and
19790 				 * we panic because either there's horrible
19791 				 * heap corruption, and/or programming mistake.
19792 				 */
19793 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19794 				if (pbuf_idx < 0) {
19795 					cmn_err(CE_PANIC, "tcp_multisend: "
19796 					    "payload buffer logic error "
19797 					    "detected for tcp %p mmd %p "
19798 					    "pbuf %p (%d)\n",
19799 					    (void *)tcp, (void *)mmd,
19800 					    (void *)md_pbuf, pbuf_idx);
19801 				}
19802 
19803 				ASSERT(max_pld > 0);
19804 				--max_pld;
19805 				add_buffer = B_FALSE;
19806 			}
19807 
19808 			ASSERT(md_mp_head != NULL);
19809 			ASSERT(md_pbuf != NULL);
19810 			ASSERT(md_pbuf_nxt == NULL);
19811 			ASSERT(pbuf_idx != -1);
19812 			ASSERT(pbuf_idx_nxt == -1);
19813 			ASSERT(*usable > 0);
19814 
19815 			/*
19816 			 * We spillover to the next payload buffer only
19817 			 * if all of the following is true:
19818 			 *
19819 			 *   1. There is not enough data on the current
19820 			 *	payload buffer to make up `len',
19821 			 *   2. We are allowed to send `len',
19822 			 *   3. The next payload buffer length is large
19823 			 *	enough to accomodate `spill'.
19824 			 */
19825 			if ((spill = len - *tail_unsent) > 0 &&
19826 			    *usable >= len &&
19827 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19828 			    max_pld > 0) {
19829 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19830 				if (md_pbuf_nxt == NULL) {
19831 					TCP_STAT(tcps, tcp_mdt_allocfail);
19832 					goto legacy_send; /* out_of_mem */
19833 				}
19834 
19835 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19836 				    zc_cap != NULL) {
19837 					if (!ip_md_zcopy_attr(mmd, NULL,
19838 					    zc_cap->ill_zerocopy_flags)) {
19839 						freeb(md_pbuf_nxt);
19840 						TCP_STAT(tcps,
19841 						    tcp_mdt_allocfail);
19842 						/* out_of_mem */
19843 						goto legacy_send;
19844 					}
19845 					zcopy = B_TRUE;
19846 				}
19847 
19848 				/*
19849 				 * See comments above on the first call to
19850 				 * mmd_addpldbuf for explanation on the panic.
19851 				 */
19852 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19853 				if (pbuf_idx_nxt < 0) {
19854 					panic("tcp_multisend: "
19855 					    "next payload buffer logic error "
19856 					    "detected for tcp %p mmd %p "
19857 					    "pbuf %p (%d)\n",
19858 					    (void *)tcp, (void *)mmd,
19859 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19860 				}
19861 
19862 				ASSERT(max_pld > 0);
19863 				--max_pld;
19864 			} else if (spill > 0) {
19865 				/*
19866 				 * If there's a spillover, but the following
19867 				 * xmit_tail couldn't give us enough octets
19868 				 * to reach "len", then stop the current
19869 				 * Multidata creation and let the legacy
19870 				 * tcp_send() path take over.  We don't want
19871 				 * to send the tiny segment as part of this
19872 				 * Multidata for performance reasons; instead,
19873 				 * we let the legacy path deal with grouping
19874 				 * it with the subsequent small mblks.
19875 				 */
19876 				if (*usable >= len &&
19877 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19878 					max_pld = 0;
19879 					break;	/* done */
19880 				}
19881 
19882 				/*
19883 				 * We can't spillover, and we are near
19884 				 * the end of the current payload buffer,
19885 				 * so send what's left.
19886 				 */
19887 				ASSERT(*tail_unsent > 0);
19888 				len = *tail_unsent;
19889 			}
19890 
19891 			/* tail_unsent is negated if there is a spillover */
19892 			*tail_unsent -= len;
19893 			*usable -= len;
19894 			ASSERT(*usable >= 0);
19895 
19896 			if (*usable < mss)
19897 				seg_len = *usable;
19898 			/*
19899 			 * Sender SWS avoidance; see comments in tcp_send();
19900 			 * everything else is the same, except that we only
19901 			 * do this here if there is no more data to be sent
19902 			 * following the current xmit_tail.  We don't check
19903 			 * for 1-byte urgent data because we shouldn't get
19904 			 * here if TCP_URG_VALID is set.
19905 			 */
19906 			if (*usable > 0 && *usable < mss &&
19907 			    ((md_pbuf_nxt == NULL &&
19908 			    (*xmit_tail)->b_cont == NULL) ||
19909 			    (md_pbuf_nxt != NULL &&
19910 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19911 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19912 			    (tcp->tcp_unsent -
19913 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19914 			    !tcp->tcp_zero_win_probe) {
19915 				if ((*snxt + len) == tcp->tcp_snxt &&
19916 				    (*snxt + len) == tcp->tcp_suna) {
19917 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19918 				}
19919 				done = B_TRUE;
19920 			}
19921 
19922 			/*
19923 			 * Prime pump for IP's checksumming on our behalf;
19924 			 * include the adjustment for a source route if any.
19925 			 * Do this only for software/partial hardware checksum
19926 			 * offload, as this field gets zeroed out later for
19927 			 * the full hardware checksum offload case.
19928 			 */
19929 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19930 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19931 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19932 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19933 			}
19934 
19935 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19936 			*snxt += len;
19937 
19938 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19939 			/*
19940 			 * We set the PUSH bit only if TCP has no more buffered
19941 			 * data to be transmitted (or if sender SWS avoidance
19942 			 * takes place), as opposed to setting it for every
19943 			 * last packet in the burst.
19944 			 */
19945 			if (done ||
19946 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19947 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19948 
19949 			/*
19950 			 * Set FIN bit if this is our last segment; snxt
19951 			 * already includes its length, and it will not
19952 			 * be adjusted after this point.
19953 			 */
19954 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19955 			    *snxt == tcp->tcp_fss) {
19956 				if (!tcp->tcp_fin_acked) {
19957 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19958 					BUMP_MIB(&tcps->tcps_mib,
19959 					    tcpOutControl);
19960 				}
19961 				if (!tcp->tcp_fin_sent) {
19962 					tcp->tcp_fin_sent = B_TRUE;
19963 					/*
19964 					 * tcp state must be ESTABLISHED
19965 					 * in order for us to get here in
19966 					 * the first place.
19967 					 */
19968 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19969 
19970 					/*
19971 					 * Upon returning from this routine,
19972 					 * tcp_wput_data() will set tcp_snxt
19973 					 * to be equal to snxt + tcp_fin_sent.
19974 					 * This is essentially the same as
19975 					 * setting it to tcp_fss + 1.
19976 					 */
19977 				}
19978 			}
19979 
19980 			tcp->tcp_last_sent_len = (ushort_t)len;
19981 
19982 			len += tcp_hdr_len;
19983 			if (tcp->tcp_ipversion == IPV4_VERSION)
19984 				tcp->tcp_ipha->ipha_length = htons(len);
19985 			else
19986 				tcp->tcp_ip6h->ip6_plen = htons(len -
19987 				    ((char *)&tcp->tcp_ip6h[1] -
19988 				    tcp->tcp_iphc));
19989 
19990 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19991 
19992 			/* setup header fragment */
19993 			PDESC_HDR_ADD(pkt_info,
19994 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19995 			    tcp->tcp_mdt_hdr_head,		/* head room */
19996 			    tcp_hdr_len,			/* len */
19997 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19998 
19999 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20000 			    hdr_frag_sz);
20001 			ASSERT(MBLKIN(md_hbuf,
20002 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20003 			    PDESC_HDRSIZE(pkt_info)));
20004 
20005 			/* setup first payload fragment */
20006 			PDESC_PLD_INIT(pkt_info);
20007 			PDESC_PLD_SPAN_ADD(pkt_info,
20008 			    pbuf_idx,				/* index */
20009 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20010 			    tcp->tcp_last_sent_len);		/* len */
20011 
20012 			/* create a split-packet in case of a spillover */
20013 			if (md_pbuf_nxt != NULL) {
20014 				ASSERT(spill > 0);
20015 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20016 				ASSERT(!add_buffer);
20017 
20018 				md_pbuf = md_pbuf_nxt;
20019 				md_pbuf_nxt = NULL;
20020 				pbuf_idx = pbuf_idx_nxt;
20021 				pbuf_idx_nxt = -1;
20022 				cur_pld_off = spill;
20023 
20024 				/* trim out first payload fragment */
20025 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20026 
20027 				/* setup second payload fragment */
20028 				PDESC_PLD_SPAN_ADD(pkt_info,
20029 				    pbuf_idx,			/* index */
20030 				    md_pbuf->b_rptr,		/* start */
20031 				    spill);			/* len */
20032 
20033 				if ((*xmit_tail)->b_next == NULL) {
20034 					/*
20035 					 * Store the lbolt used for RTT
20036 					 * estimation. We can only record one
20037 					 * timestamp per mblk so we do it when
20038 					 * we reach the end of the payload
20039 					 * buffer.  Also we only take a new
20040 					 * timestamp sample when the previous
20041 					 * timed data from the same mblk has
20042 					 * been ack'ed.
20043 					 */
20044 					(*xmit_tail)->b_prev = local_time;
20045 					(*xmit_tail)->b_next =
20046 					    (mblk_t *)(uintptr_t)first_snxt;
20047 				}
20048 
20049 				first_snxt = *snxt - spill;
20050 
20051 				/*
20052 				 * Advance xmit_tail; usable could be 0 by
20053 				 * the time we got here, but we made sure
20054 				 * above that we would only spillover to
20055 				 * the next data block if usable includes
20056 				 * the spilled-over amount prior to the
20057 				 * subtraction.  Therefore, we are sure
20058 				 * that xmit_tail->b_cont can't be NULL.
20059 				 */
20060 				ASSERT((*xmit_tail)->b_cont != NULL);
20061 				*xmit_tail = (*xmit_tail)->b_cont;
20062 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20063 				    (uintptr_t)INT_MAX);
20064 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20065 			} else {
20066 				cur_pld_off += tcp->tcp_last_sent_len;
20067 			}
20068 
20069 			/*
20070 			 * Fill in the header using the template header, and
20071 			 * add options such as time-stamp, ECN and/or SACK,
20072 			 * as needed.
20073 			 */
20074 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20075 			    (clock_t)local_time, num_sack_blk);
20076 
20077 			/* take care of some IP header businesses */
20078 			if (af == AF_INET) {
20079 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20080 
20081 				ASSERT(OK_32PTR((uchar_t *)ipha));
20082 				ASSERT(PDESC_HDRL(pkt_info) >=
20083 				    IP_SIMPLE_HDR_LENGTH);
20084 				ASSERT(ipha->ipha_version_and_hdr_length ==
20085 				    IP_SIMPLE_HDR_VERSION);
20086 
20087 				/*
20088 				 * Assign ident value for current packet; see
20089 				 * related comments in ip_wput_ire() about the
20090 				 * contract private interface with clustering
20091 				 * group.
20092 				 */
20093 				clusterwide = B_FALSE;
20094 				if (cl_inet_ipident != NULL) {
20095 					ASSERT(cl_inet_isclusterwide != NULL);
20096 					if ((*cl_inet_isclusterwide)(stack_id,
20097 					    IPPROTO_IP, AF_INET,
20098 					    (uint8_t *)(uintptr_t)src, NULL)) {
20099 						ipha->ipha_ident =
20100 						    (*cl_inet_ipident)(stack_id,
20101 						    IPPROTO_IP, AF_INET,
20102 						    (uint8_t *)(uintptr_t)src,
20103 						    (uint8_t *)(uintptr_t)dst,
20104 						    NULL);
20105 						clusterwide = B_TRUE;
20106 					}
20107 				}
20108 
20109 				if (!clusterwide) {
20110 					ipha->ipha_ident = (uint16_t)
20111 					    atomic_add_32_nv(
20112 						&ire->ire_ident, 1);
20113 				}
20114 #ifndef _BIG_ENDIAN
20115 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20116 				    (ipha->ipha_ident >> 8);
20117 #endif
20118 			} else {
20119 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20120 
20121 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20122 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20123 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20124 				ASSERT(PDESC_HDRL(pkt_info) >=
20125 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20126 				    TCP_CHECKSUM_SIZE));
20127 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20128 
20129 				if (tcp->tcp_ip_forward_progress) {
20130 					rconfirm = B_TRUE;
20131 					tcp->tcp_ip_forward_progress = B_FALSE;
20132 				}
20133 			}
20134 
20135 			/* at least one payload span, and at most two */
20136 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20137 
20138 			/* add the packet descriptor to Multidata */
20139 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20140 			    KM_NOSLEEP)) == NULL) {
20141 				/*
20142 				 * Any failure other than ENOMEM indicates
20143 				 * that we have passed in invalid pkt_info
20144 				 * or parameters to mmd_addpdesc, which must
20145 				 * not happen.
20146 				 *
20147 				 * EINVAL is a result of failure on boundary
20148 				 * checks against the pkt_info contents.  It
20149 				 * should not happen, and we panic because
20150 				 * either there's horrible heap corruption,
20151 				 * and/or programming mistake.
20152 				 */
20153 				if (err != ENOMEM) {
20154 					cmn_err(CE_PANIC, "tcp_multisend: "
20155 					    "pdesc logic error detected for "
20156 					    "tcp %p mmd %p pinfo %p (%d)\n",
20157 					    (void *)tcp, (void *)mmd,
20158 					    (void *)pkt_info, err);
20159 				}
20160 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20161 				goto legacy_send; /* out_of_mem */
20162 			}
20163 			ASSERT(pkt != NULL);
20164 
20165 			/* calculate IP header and TCP checksums */
20166 			if (af == AF_INET) {
20167 				/* calculate pseudo-header checksum */
20168 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20169 				    (src >> 16) + (src & 0xFFFF);
20170 
20171 				/* offset for TCP header checksum */
20172 				up = IPH_TCPH_CHECKSUMP(ipha,
20173 				    IP_SIMPLE_HDR_LENGTH);
20174 			} else {
20175 				up = (uint16_t *)&ip6h->ip6_src;
20176 
20177 				/* calculate pseudo-header checksum */
20178 				cksum = up[0] + up[1] + up[2] + up[3] +
20179 				    up[4] + up[5] + up[6] + up[7] +
20180 				    up[8] + up[9] + up[10] + up[11] +
20181 				    up[12] + up[13] + up[14] + up[15];
20182 
20183 				/* Fold the initial sum */
20184 				cksum = (cksum & 0xffff) + (cksum >> 16);
20185 
20186 				up = (uint16_t *)(((uchar_t *)ip6h) +
20187 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20188 			}
20189 
20190 			if (hwcksum_flags & HCK_FULLCKSUM) {
20191 				/* clear checksum field for hardware */
20192 				*up = 0;
20193 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20194 				uint32_t sum;
20195 
20196 				/* pseudo-header checksumming */
20197 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20198 				sum = (sum & 0xFFFF) + (sum >> 16);
20199 				*up = (sum & 0xFFFF) + (sum >> 16);
20200 			} else {
20201 				/* software checksumming */
20202 				TCP_STAT(tcps, tcp_out_sw_cksum);
20203 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20204 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20205 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20206 				    cksum + IP_TCP_CSUM_COMP);
20207 				if (*up == 0)
20208 					*up = 0xFFFF;
20209 			}
20210 
20211 			/* IPv4 header checksum */
20212 			if (af == AF_INET) {
20213 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20214 					ipha->ipha_hdr_checksum = 0;
20215 				} else {
20216 					IP_HDR_CKSUM(ipha, cksum,
20217 					    ((uint32_t *)ipha)[0],
20218 					    ((uint16_t *)ipha)[4]);
20219 				}
20220 			}
20221 
20222 			if (af == AF_INET &&
20223 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20224 			    af == AF_INET6 &&
20225 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20226 				mblk_t	*mp, *mp1;
20227 				uchar_t	*hdr_rptr, *hdr_wptr;
20228 				uchar_t	*pld_rptr, *pld_wptr;
20229 
20230 				/*
20231 				 * We reconstruct a pseudo packet for the hooks
20232 				 * framework using mmd_transform_link().
20233 				 * If it is a split packet we pullup the
20234 				 * payload. FW_HOOKS expects a pkt comprising
20235 				 * of two mblks: a header and the payload.
20236 				 */
20237 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20238 					TCP_STAT(tcps, tcp_mdt_allocfail);
20239 					goto legacy_send;
20240 				}
20241 
20242 				if (pkt_info->pld_cnt > 1) {
20243 					/* split payload, more than one pld */
20244 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20245 					    NULL) {
20246 						freemsg(mp);
20247 						TCP_STAT(tcps,
20248 						    tcp_mdt_allocfail);
20249 						goto legacy_send;
20250 					}
20251 					freemsg(mp->b_cont);
20252 					mp->b_cont = mp1;
20253 				} else {
20254 					mp1 = mp->b_cont;
20255 				}
20256 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20257 
20258 				/*
20259 				 * Remember the message offsets. This is so we
20260 				 * can detect changes when we return from the
20261 				 * FW_HOOKS callbacks.
20262 				 */
20263 				hdr_rptr = mp->b_rptr;
20264 				hdr_wptr = mp->b_wptr;
20265 				pld_rptr = mp->b_cont->b_rptr;
20266 				pld_wptr = mp->b_cont->b_wptr;
20267 
20268 				if (af == AF_INET) {
20269 					DTRACE_PROBE4(
20270 					    ip4__physical__out__start,
20271 					    ill_t *, NULL,
20272 					    ill_t *, ill,
20273 					    ipha_t *, ipha,
20274 					    mblk_t *, mp);
20275 					FW_HOOKS(
20276 					    ipst->ips_ip4_physical_out_event,
20277 					    ipst->ips_ipv4firewall_physical_out,
20278 					    NULL, ill, ipha, mp, mp, 0, ipst);
20279 					DTRACE_PROBE1(
20280 					    ip4__physical__out__end,
20281 					    mblk_t *, mp);
20282 				} else {
20283 					DTRACE_PROBE4(
20284 					    ip6__physical__out_start,
20285 					    ill_t *, NULL,
20286 					    ill_t *, ill,
20287 					    ip6_t *, ip6h,
20288 					    mblk_t *, mp);
20289 					FW_HOOKS6(
20290 					    ipst->ips_ip6_physical_out_event,
20291 					    ipst->ips_ipv6firewall_physical_out,
20292 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20293 					DTRACE_PROBE1(
20294 					    ip6__physical__out__end,
20295 					    mblk_t *, mp);
20296 				}
20297 
20298 				if (mp == NULL ||
20299 				    (mp1 = mp->b_cont) == NULL ||
20300 				    mp->b_rptr != hdr_rptr ||
20301 				    mp->b_wptr != hdr_wptr ||
20302 				    mp1->b_rptr != pld_rptr ||
20303 				    mp1->b_wptr != pld_wptr ||
20304 				    mp1->b_cont != NULL) {
20305 					/*
20306 					 * We abandon multidata processing and
20307 					 * return to the normal path, either
20308 					 * when a packet is blocked, or when
20309 					 * the boundaries of header buffer or
20310 					 * payload buffer have been changed by
20311 					 * FW_HOOKS[6].
20312 					 */
20313 					if (mp != NULL)
20314 						freemsg(mp);
20315 					goto legacy_send;
20316 				}
20317 				/* Finished with the pseudo packet */
20318 				freemsg(mp);
20319 			}
20320 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
20321 			    ill, ipha, ip6h);
20322 			/* advance header offset */
20323 			cur_hdr_off += hdr_frag_sz;
20324 
20325 			obbytes += tcp->tcp_last_sent_len;
20326 			++obsegs;
20327 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20328 		    *tail_unsent > 0);
20329 
20330 		if ((*xmit_tail)->b_next == NULL) {
20331 			/*
20332 			 * Store the lbolt used for RTT estimation. We can only
20333 			 * record one timestamp per mblk so we do it when we
20334 			 * reach the end of the payload buffer. Also we only
20335 			 * take a new timestamp sample when the previous timed
20336 			 * data from the same mblk has been ack'ed.
20337 			 */
20338 			(*xmit_tail)->b_prev = local_time;
20339 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20340 		}
20341 
20342 		ASSERT(*tail_unsent >= 0);
20343 		if (*tail_unsent > 0) {
20344 			/*
20345 			 * We got here because we broke out of the above
20346 			 * loop due to of one of the following cases:
20347 			 *
20348 			 *   1. len < adjusted MSS (i.e. small),
20349 			 *   2. Sender SWS avoidance,
20350 			 *   3. max_pld is zero.
20351 			 *
20352 			 * We are done for this Multidata, so trim our
20353 			 * last payload buffer (if any) accordingly.
20354 			 */
20355 			if (md_pbuf != NULL)
20356 				md_pbuf->b_wptr -= *tail_unsent;
20357 		} else if (*usable > 0) {
20358 			*xmit_tail = (*xmit_tail)->b_cont;
20359 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20360 			    (uintptr_t)INT_MAX);
20361 			*tail_unsent = (int)MBLKL(*xmit_tail);
20362 			add_buffer = B_TRUE;
20363 		}
20364 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20365 	    (tcp_mdt_chain || max_pld > 0));
20366 
20367 	if (md_mp_head != NULL) {
20368 		/* send everything down */
20369 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20370 		    &rconfirm);
20371 	}
20372 
20373 #undef PREP_NEW_MULTIDATA
20374 #undef PREP_NEW_PBUF
20375 #undef IPVER
20376 
20377 	IRE_REFRELE(ire);
20378 	return (0);
20379 }
20380 
20381 /*
20382  * A wrapper function for sending one or more Multidata messages down to
20383  * the module below ip; this routine does not release the reference of the
20384  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20385  */
20386 static void
20387 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20388     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20389 {
20390 	uint64_t delta;
20391 	nce_t *nce;
20392 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20393 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20394 
20395 	ASSERT(ire != NULL && ill != NULL);
20396 	ASSERT(ire->ire_stq != NULL);
20397 	ASSERT(md_mp_head != NULL);
20398 	ASSERT(rconfirm != NULL);
20399 
20400 	/* adjust MIBs and IRE timestamp */
20401 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
20402 	tcp->tcp_obsegs += obsegs;
20403 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20404 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20405 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20406 
20407 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20408 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20409 	} else {
20410 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20411 	}
20412 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20413 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20414 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20415 
20416 	ire->ire_ob_pkt_count += obsegs;
20417 	if (ire->ire_ipif != NULL)
20418 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20419 	ire->ire_last_used_time = lbolt;
20420 
20421 	if (ipst->ips_ipobs_enabled) {
20422 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
20423 		pdesc_t *dl_pkt;
20424 		pdescinfo_t pinfo;
20425 		mblk_t *nmp;
20426 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
20427 
20428 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
20429 		    (dl_pkt != NULL);
20430 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
20431 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
20432 				continue;
20433 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
20434 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
20435 			freemsg(nmp);
20436 		}
20437 	}
20438 
20439 	/* send it down */
20440 	putnext(ire->ire_stq, md_mp_head);
20441 
20442 	/* we're done for TCP/IPv4 */
20443 	if (tcp->tcp_ipversion == IPV4_VERSION)
20444 		return;
20445 
20446 	nce = ire->ire_nce;
20447 
20448 	ASSERT(nce != NULL);
20449 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20450 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20451 
20452 	/* reachability confirmation? */
20453 	if (*rconfirm) {
20454 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20455 		if (nce->nce_state != ND_REACHABLE) {
20456 			mutex_enter(&nce->nce_lock);
20457 			nce->nce_state = ND_REACHABLE;
20458 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20459 			mutex_exit(&nce->nce_lock);
20460 			(void) untimeout(nce->nce_timeout_id);
20461 			if (ip_debug > 2) {
20462 				/* ip1dbg */
20463 				pr_addr_dbg("tcp_multisend_data: state "
20464 				    "for %s changed to REACHABLE\n",
20465 				    AF_INET6, &ire->ire_addr_v6);
20466 			}
20467 		}
20468 		/* reset transport reachability confirmation */
20469 		*rconfirm = B_FALSE;
20470 	}
20471 
20472 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20473 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20474 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20475 
20476 	if (delta > (uint64_t)ill->ill_reachable_time) {
20477 		mutex_enter(&nce->nce_lock);
20478 		switch (nce->nce_state) {
20479 		case ND_REACHABLE:
20480 		case ND_STALE:
20481 			/*
20482 			 * ND_REACHABLE is identical to ND_STALE in this
20483 			 * specific case. If reachable time has expired for
20484 			 * this neighbor (delta is greater than reachable
20485 			 * time), conceptually, the neighbor cache is no
20486 			 * longer in REACHABLE state, but already in STALE
20487 			 * state.  So the correct transition here is to
20488 			 * ND_DELAY.
20489 			 */
20490 			nce->nce_state = ND_DELAY;
20491 			mutex_exit(&nce->nce_lock);
20492 			NDP_RESTART_TIMER(nce,
20493 			    ipst->ips_delay_first_probe_time);
20494 			if (ip_debug > 3) {
20495 				/* ip2dbg */
20496 				pr_addr_dbg("tcp_multisend_data: state "
20497 				    "for %s changed to DELAY\n",
20498 				    AF_INET6, &ire->ire_addr_v6);
20499 			}
20500 			break;
20501 		case ND_DELAY:
20502 		case ND_PROBE:
20503 			mutex_exit(&nce->nce_lock);
20504 			/* Timers have already started */
20505 			break;
20506 		case ND_UNREACHABLE:
20507 			/*
20508 			 * ndp timer has detected that this nce is
20509 			 * unreachable and initiated deleting this nce
20510 			 * and all its associated IREs. This is a race
20511 			 * where we found the ire before it was deleted
20512 			 * and have just sent out a packet using this
20513 			 * unreachable nce.
20514 			 */
20515 			mutex_exit(&nce->nce_lock);
20516 			break;
20517 		default:
20518 			ASSERT(0);
20519 		}
20520 	}
20521 }
20522 
20523 /*
20524  * Derived from tcp_send_data().
20525  */
20526 static void
20527 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20528     int num_lso_seg)
20529 {
20530 	ipha_t		*ipha;
20531 	mblk_t		*ire_fp_mp;
20532 	uint_t		ire_fp_mp_len;
20533 	uint32_t	hcksum_txflags = 0;
20534 	ipaddr_t	src;
20535 	ipaddr_t	dst;
20536 	uint32_t	cksum;
20537 	uint16_t	*up;
20538 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20539 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20540 
20541 	ASSERT(DB_TYPE(mp) == M_DATA);
20542 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20543 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20544 	ASSERT(tcp->tcp_connp != NULL);
20545 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20546 
20547 	ipha = (ipha_t *)mp->b_rptr;
20548 	src = ipha->ipha_src;
20549 	dst = ipha->ipha_dst;
20550 
20551 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
20552 
20553 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20554 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20555 	    num_lso_seg);
20556 #ifndef _BIG_ENDIAN
20557 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20558 #endif
20559 	if (tcp->tcp_snd_zcopy_aware) {
20560 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20561 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20562 			mp = tcp_zcopy_disable(tcp, mp);
20563 	}
20564 
20565 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20566 		ASSERT(ill->ill_hcksum_capab != NULL);
20567 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20568 	}
20569 
20570 	/*
20571 	 * Since the TCP checksum should be recalculated by h/w, we can just
20572 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20573 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20574 	 * The partial pseudo-header excludes TCP length, that was calculated
20575 	 * in tcp_send(), so to zero *up before further processing.
20576 	 */
20577 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20578 
20579 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20580 	*up = 0;
20581 
20582 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20583 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20584 
20585 	/*
20586 	 * Append LSO flags and mss to the mp.
20587 	 */
20588 	lso_info_set(mp, mss, HW_LSO);
20589 
20590 	ipha->ipha_fragment_offset_and_flags |=
20591 	    (uint32_t)htons(ire->ire_frag_flag);
20592 
20593 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20594 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20595 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20596 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20597 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20598 
20599 	UPDATE_OB_PKT_COUNT(ire);
20600 	ire->ire_last_used_time = lbolt;
20601 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20602 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20603 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20604 	    ntohs(ipha->ipha_length));
20605 
20606 	DTRACE_PROBE4(ip4__physical__out__start,
20607 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
20608 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
20609 	    ipst->ips_ipv4firewall_physical_out, NULL,
20610 	    ill, ipha, mp, mp, 0, ipst);
20611 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20612 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
20613 
20614 	if (mp != NULL) {
20615 		if (ipst->ips_ipobs_enabled) {
20616 			zoneid_t szone;
20617 
20618 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
20619 			    ipst, ALL_ZONES);
20620 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
20621 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
20622 		}
20623 
20624 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
20625 	}
20626 }
20627 
20628 /*
20629  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20630  * scheme, and returns one of the following:
20631  *
20632  * -1 = failed allocation.
20633  *  0 = success; burst count reached, or usable send window is too small,
20634  *      and that we'd rather wait until later before sending again.
20635  *  1 = success; we are called from tcp_multisend(), and both usable send
20636  *      window and tail_unsent are greater than the MDT threshold, and thus
20637  *      Multidata Transmit should be used instead.
20638  */
20639 static int
20640 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20641     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20642     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20643     const int mdt_thres)
20644 {
20645 	int num_burst_seg = tcp->tcp_snd_burst;
20646 	ire_t		*ire = NULL;
20647 	ill_t		*ill = NULL;
20648 	mblk_t		*ire_fp_mp = NULL;
20649 	uint_t		ire_fp_mp_len = 0;
20650 	int		num_lso_seg = 1;
20651 	uint_t		lso_usable;
20652 	boolean_t	do_lso_send = B_FALSE;
20653 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20654 
20655 	/*
20656 	 * Check LSO capability before any further work. And the similar check
20657 	 * need to be done in for(;;) loop.
20658 	 * LSO will be deployed when therer is more than one mss of available
20659 	 * data and a burst transmission is allowed.
20660 	 */
20661 	if (tcp->tcp_lso &&
20662 	    (tcp->tcp_valid_bits == 0 ||
20663 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20664 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20665 		/*
20666 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20667 		 * Double check LSO usability before going further, since the
20668 		 * underlying interface could have been changed. In case of any
20669 		 * change of LSO capability, set tcp_ire_ill_check_done to
20670 		 * B_FALSE to force to check the ILL with the next send.
20671 		 */
20672 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
20673 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
20674 			/*
20675 			 * Enable LSO with this transmission.
20676 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
20677 			 * IRE_REFRELE(ire) should be called before return.
20678 			 */
20679 			do_lso_send = B_TRUE;
20680 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
20681 			ire_fp_mp_len = MBLKL(ire_fp_mp);
20682 			/* Round up to multiple of 4 */
20683 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
20684 		} else {
20685 			tcp->tcp_lso = B_FALSE;
20686 			tcp->tcp_ire_ill_check_done = B_FALSE;
20687 			do_lso_send = B_FALSE;
20688 			ill = NULL;
20689 		}
20690 	}
20691 
20692 	for (;;) {
20693 		struct datab	*db;
20694 		tcph_t		*tcph;
20695 		uint32_t	sum;
20696 		mblk_t		*mp, *mp1;
20697 		uchar_t		*rptr;
20698 		int		len;
20699 
20700 		/*
20701 		 * If we're called by tcp_multisend(), and the amount of
20702 		 * sendable data as well as the size of current xmit_tail
20703 		 * is beyond the MDT threshold, return to the caller and
20704 		 * let the large data transmit be done using MDT.
20705 		 */
20706 		if (*usable > 0 && *usable > mdt_thres &&
20707 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20708 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20709 			ASSERT(tcp->tcp_mdt);
20710 			return (1);	/* success; do large send */
20711 		}
20712 
20713 		if (num_burst_seg == 0)
20714 			break;		/* success; burst count reached */
20715 
20716 		/*
20717 		 * Calculate the maximum payload length we can send in *one*
20718 		 * time.
20719 		 */
20720 		if (do_lso_send) {
20721 			/*
20722 			 * Check whether need to do LSO any more.
20723 			 */
20724 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20725 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
20726 				lso_usable = MIN(lso_usable,
20727 				    num_burst_seg * mss);
20728 
20729 				num_lso_seg = lso_usable / mss;
20730 				if (lso_usable % mss) {
20731 					num_lso_seg++;
20732 					tcp->tcp_last_sent_len = (ushort_t)
20733 					    (lso_usable % mss);
20734 				} else {
20735 					tcp->tcp_last_sent_len = (ushort_t)mss;
20736 				}
20737 			} else {
20738 				do_lso_send = B_FALSE;
20739 				num_lso_seg = 1;
20740 				lso_usable = mss;
20741 			}
20742 		}
20743 
20744 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
20745 
20746 		/*
20747 		 * Adjust num_burst_seg here.
20748 		 */
20749 		num_burst_seg -= num_lso_seg;
20750 
20751 		len = mss;
20752 		if (len > *usable) {
20753 			ASSERT(do_lso_send == B_FALSE);
20754 
20755 			len = *usable;
20756 			if (len <= 0) {
20757 				/* Terminate the loop */
20758 				break;	/* success; too small */
20759 			}
20760 			/*
20761 			 * Sender silly-window avoidance.
20762 			 * Ignore this if we are going to send a
20763 			 * zero window probe out.
20764 			 *
20765 			 * TODO: force data into microscopic window?
20766 			 *	==> (!pushed || (unsent > usable))
20767 			 */
20768 			if (len < (tcp->tcp_max_swnd >> 1) &&
20769 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20770 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20771 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20772 				/*
20773 				 * If the retransmit timer is not running
20774 				 * we start it so that we will retransmit
20775 				 * in the case when the the receiver has
20776 				 * decremented the window.
20777 				 */
20778 				if (*snxt == tcp->tcp_snxt &&
20779 				    *snxt == tcp->tcp_suna) {
20780 					/*
20781 					 * We are not supposed to send
20782 					 * anything.  So let's wait a little
20783 					 * bit longer before breaking SWS
20784 					 * avoidance.
20785 					 *
20786 					 * What should the value be?
20787 					 * Suggestion: MAX(init rexmit time,
20788 					 * tcp->tcp_rto)
20789 					 */
20790 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20791 				}
20792 				break;	/* success; too small */
20793 			}
20794 		}
20795 
20796 		tcph = tcp->tcp_tcph;
20797 
20798 		/*
20799 		 * The reason to adjust len here is that we need to set flags
20800 		 * and calculate checksum.
20801 		 */
20802 		if (do_lso_send)
20803 			len = lso_usable;
20804 
20805 		*usable -= len; /* Approximate - can be adjusted later */
20806 		if (*usable > 0)
20807 			tcph->th_flags[0] = TH_ACK;
20808 		else
20809 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20810 
20811 		/*
20812 		 * Prime pump for IP's checksumming on our behalf
20813 		 * Include the adjustment for a source route if any.
20814 		 */
20815 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20816 		sum = (sum >> 16) + (sum & 0xFFFF);
20817 		U16_TO_ABE16(sum, tcph->th_sum);
20818 
20819 		U32_TO_ABE32(*snxt, tcph->th_seq);
20820 
20821 		/*
20822 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20823 		 * set.  For the case when TCP_FSS_VALID is the only valid
20824 		 * bit (normal active close), branch off only when we think
20825 		 * that the FIN flag needs to be set.  Note for this case,
20826 		 * that (snxt + len) may not reflect the actual seg_len,
20827 		 * as len may be further reduced in tcp_xmit_mp().  If len
20828 		 * gets modified, we will end up here again.
20829 		 */
20830 		if (tcp->tcp_valid_bits != 0 &&
20831 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20832 		    ((*snxt + len) == tcp->tcp_fss))) {
20833 			uchar_t		*prev_rptr;
20834 			uint32_t	prev_snxt = tcp->tcp_snxt;
20835 
20836 			if (*tail_unsent == 0) {
20837 				ASSERT((*xmit_tail)->b_cont != NULL);
20838 				*xmit_tail = (*xmit_tail)->b_cont;
20839 				prev_rptr = (*xmit_tail)->b_rptr;
20840 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20841 				    (*xmit_tail)->b_rptr);
20842 			} else {
20843 				prev_rptr = (*xmit_tail)->b_rptr;
20844 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20845 				    *tail_unsent;
20846 			}
20847 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20848 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20849 			/* Restore tcp_snxt so we get amount sent right. */
20850 			tcp->tcp_snxt = prev_snxt;
20851 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20852 				/*
20853 				 * If the previous timestamp is still in use,
20854 				 * don't stomp on it.
20855 				 */
20856 				if ((*xmit_tail)->b_next == NULL) {
20857 					(*xmit_tail)->b_prev = local_time;
20858 					(*xmit_tail)->b_next =
20859 					    (mblk_t *)(uintptr_t)(*snxt);
20860 				}
20861 			} else
20862 				(*xmit_tail)->b_rptr = prev_rptr;
20863 
20864 			if (mp == NULL) {
20865 				if (ire != NULL)
20866 					IRE_REFRELE(ire);
20867 				return (-1);
20868 			}
20869 			mp1 = mp->b_cont;
20870 
20871 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
20872 				tcp->tcp_last_sent_len = (ushort_t)len;
20873 			while (mp1->b_cont) {
20874 				*xmit_tail = (*xmit_tail)->b_cont;
20875 				(*xmit_tail)->b_prev = local_time;
20876 				(*xmit_tail)->b_next =
20877 				    (mblk_t *)(uintptr_t)(*snxt);
20878 				mp1 = mp1->b_cont;
20879 			}
20880 			*snxt += len;
20881 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20882 			BUMP_LOCAL(tcp->tcp_obsegs);
20883 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20884 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20885 			tcp_send_data(tcp, q, mp);
20886 			continue;
20887 		}
20888 
20889 		*snxt += len;	/* Adjust later if we don't send all of len */
20890 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20891 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20892 
20893 		if (*tail_unsent) {
20894 			/* Are the bytes above us in flight? */
20895 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20896 			if (rptr != (*xmit_tail)->b_rptr) {
20897 				*tail_unsent -= len;
20898 				if (len <= mss) /* LSO is unusable */
20899 					tcp->tcp_last_sent_len = (ushort_t)len;
20900 				len += tcp_hdr_len;
20901 				if (tcp->tcp_ipversion == IPV4_VERSION)
20902 					tcp->tcp_ipha->ipha_length = htons(len);
20903 				else
20904 					tcp->tcp_ip6h->ip6_plen =
20905 					    htons(len -
20906 					    ((char *)&tcp->tcp_ip6h[1] -
20907 					    tcp->tcp_iphc));
20908 				mp = dupb(*xmit_tail);
20909 				if (mp == NULL) {
20910 					if (ire != NULL)
20911 						IRE_REFRELE(ire);
20912 					return (-1);	/* out_of_mem */
20913 				}
20914 				mp->b_rptr = rptr;
20915 				/*
20916 				 * If the old timestamp is no longer in use,
20917 				 * sample a new timestamp now.
20918 				 */
20919 				if ((*xmit_tail)->b_next == NULL) {
20920 					(*xmit_tail)->b_prev = local_time;
20921 					(*xmit_tail)->b_next =
20922 					    (mblk_t *)(uintptr_t)(*snxt-len);
20923 				}
20924 				goto must_alloc;
20925 			}
20926 		} else {
20927 			*xmit_tail = (*xmit_tail)->b_cont;
20928 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20929 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20930 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20931 			    (*xmit_tail)->b_rptr);
20932 		}
20933 
20934 		(*xmit_tail)->b_prev = local_time;
20935 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20936 
20937 		*tail_unsent -= len;
20938 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
20939 			tcp->tcp_last_sent_len = (ushort_t)len;
20940 
20941 		len += tcp_hdr_len;
20942 		if (tcp->tcp_ipversion == IPV4_VERSION)
20943 			tcp->tcp_ipha->ipha_length = htons(len);
20944 		else
20945 			tcp->tcp_ip6h->ip6_plen = htons(len -
20946 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20947 
20948 		mp = dupb(*xmit_tail);
20949 		if (mp == NULL) {
20950 			if (ire != NULL)
20951 				IRE_REFRELE(ire);
20952 			return (-1);	/* out_of_mem */
20953 		}
20954 
20955 		len = tcp_hdr_len;
20956 		/*
20957 		 * There are four reasons to allocate a new hdr mblk:
20958 		 *  1) The bytes above us are in use by another packet
20959 		 *  2) We don't have good alignment
20960 		 *  3) The mblk is being shared
20961 		 *  4) We don't have enough room for a header
20962 		 */
20963 		rptr = mp->b_rptr - len;
20964 		if (!OK_32PTR(rptr) ||
20965 		    ((db = mp->b_datap), db->db_ref != 2) ||
20966 		    rptr < db->db_base + ire_fp_mp_len) {
20967 			/* NOTE: we assume allocb returns an OK_32PTR */
20968 
20969 		must_alloc:;
20970 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20971 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
20972 			if (mp1 == NULL) {
20973 				freemsg(mp);
20974 				if (ire != NULL)
20975 					IRE_REFRELE(ire);
20976 				return (-1);	/* out_of_mem */
20977 			}
20978 			mp1->b_cont = mp;
20979 			mp = mp1;
20980 			/* Leave room for Link Level header */
20981 			len = tcp_hdr_len;
20982 			rptr =
20983 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
20984 			mp->b_wptr = &rptr[len];
20985 		}
20986 
20987 		/*
20988 		 * Fill in the header using the template header, and add
20989 		 * options such as time-stamp, ECN and/or SACK, as needed.
20990 		 */
20991 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20992 
20993 		mp->b_rptr = rptr;
20994 
20995 		if (*tail_unsent) {
20996 			int spill = *tail_unsent;
20997 
20998 			mp1 = mp->b_cont;
20999 			if (mp1 == NULL)
21000 				mp1 = mp;
21001 
21002 			/*
21003 			 * If we're a little short, tack on more mblks until
21004 			 * there is no more spillover.
21005 			 */
21006 			while (spill < 0) {
21007 				mblk_t *nmp;
21008 				int nmpsz;
21009 
21010 				nmp = (*xmit_tail)->b_cont;
21011 				nmpsz = MBLKL(nmp);
21012 
21013 				/*
21014 				 * Excess data in mblk; can we split it?
21015 				 * If MDT is enabled for the connection,
21016 				 * keep on splitting as this is a transient
21017 				 * send path.
21018 				 */
21019 				if (!do_lso_send && !tcp->tcp_mdt &&
21020 				    (spill + nmpsz > 0)) {
21021 					/*
21022 					 * Don't split if stream head was
21023 					 * told to break up larger writes
21024 					 * into smaller ones.
21025 					 */
21026 					if (tcp->tcp_maxpsz > 0)
21027 						break;
21028 
21029 					/*
21030 					 * Next mblk is less than SMSS/2
21031 					 * rounded up to nearest 64-byte;
21032 					 * let it get sent as part of the
21033 					 * next segment.
21034 					 */
21035 					if (tcp->tcp_localnet &&
21036 					    !tcp->tcp_cork &&
21037 					    (nmpsz < roundup((mss >> 1), 64)))
21038 						break;
21039 				}
21040 
21041 				*xmit_tail = nmp;
21042 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21043 				/* Stash for rtt use later */
21044 				(*xmit_tail)->b_prev = local_time;
21045 				(*xmit_tail)->b_next =
21046 				    (mblk_t *)(uintptr_t)(*snxt - len);
21047 				mp1->b_cont = dupb(*xmit_tail);
21048 				mp1 = mp1->b_cont;
21049 
21050 				spill += nmpsz;
21051 				if (mp1 == NULL) {
21052 					*tail_unsent = spill;
21053 					freemsg(mp);
21054 					if (ire != NULL)
21055 						IRE_REFRELE(ire);
21056 					return (-1);	/* out_of_mem */
21057 				}
21058 			}
21059 
21060 			/* Trim back any surplus on the last mblk */
21061 			if (spill >= 0) {
21062 				mp1->b_wptr -= spill;
21063 				*tail_unsent = spill;
21064 			} else {
21065 				/*
21066 				 * We did not send everything we could in
21067 				 * order to remain within the b_cont limit.
21068 				 */
21069 				*usable -= spill;
21070 				*snxt += spill;
21071 				tcp->tcp_last_sent_len += spill;
21072 				UPDATE_MIB(&tcps->tcps_mib,
21073 				    tcpOutDataBytes, spill);
21074 				/*
21075 				 * Adjust the checksum
21076 				 */
21077 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21078 				sum += spill;
21079 				sum = (sum >> 16) + (sum & 0xFFFF);
21080 				U16_TO_ABE16(sum, tcph->th_sum);
21081 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21082 					sum = ntohs(
21083 					    ((ipha_t *)rptr)->ipha_length) +
21084 					    spill;
21085 					((ipha_t *)rptr)->ipha_length =
21086 					    htons(sum);
21087 				} else {
21088 					sum = ntohs(
21089 					    ((ip6_t *)rptr)->ip6_plen) +
21090 					    spill;
21091 					((ip6_t *)rptr)->ip6_plen =
21092 					    htons(sum);
21093 				}
21094 				*tail_unsent = 0;
21095 			}
21096 		}
21097 		if (tcp->tcp_ip_forward_progress) {
21098 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21099 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21100 			tcp->tcp_ip_forward_progress = B_FALSE;
21101 		}
21102 
21103 		if (do_lso_send) {
21104 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21105 			    num_lso_seg);
21106 			tcp->tcp_obsegs += num_lso_seg;
21107 
21108 			TCP_STAT(tcps, tcp_lso_times);
21109 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21110 		} else {
21111 			tcp_send_data(tcp, q, mp);
21112 			BUMP_LOCAL(tcp->tcp_obsegs);
21113 		}
21114 	}
21115 
21116 	if (ire != NULL)
21117 		IRE_REFRELE(ire);
21118 	return (0);
21119 }
21120 
21121 /* Unlink and return any mblk that looks like it contains a MDT info */
21122 static mblk_t *
21123 tcp_mdt_info_mp(mblk_t *mp)
21124 {
21125 	mblk_t	*prev_mp;
21126 
21127 	for (;;) {
21128 		prev_mp = mp;
21129 		/* no more to process? */
21130 		if ((mp = mp->b_cont) == NULL)
21131 			break;
21132 
21133 		switch (DB_TYPE(mp)) {
21134 		case M_CTL:
21135 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21136 				continue;
21137 			ASSERT(prev_mp != NULL);
21138 			prev_mp->b_cont = mp->b_cont;
21139 			mp->b_cont = NULL;
21140 			return (mp);
21141 		default:
21142 			break;
21143 		}
21144 	}
21145 	return (mp);
21146 }
21147 
21148 /* MDT info update routine, called when IP notifies us about MDT */
21149 static void
21150 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21151 {
21152 	boolean_t prev_state;
21153 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21154 
21155 	/*
21156 	 * IP is telling us to abort MDT on this connection?  We know
21157 	 * this because the capability is only turned off when IP
21158 	 * encounters some pathological cases, e.g. link-layer change
21159 	 * where the new driver doesn't support MDT, or in situation
21160 	 * where MDT usage on the link-layer has been switched off.
21161 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21162 	 * if the link-layer doesn't support MDT, and if it does, it
21163 	 * will indicate that the feature is to be turned on.
21164 	 */
21165 	prev_state = tcp->tcp_mdt;
21166 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21167 	if (!tcp->tcp_mdt && !first) {
21168 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21169 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21170 		    (void *)tcp->tcp_connp));
21171 	}
21172 
21173 	/*
21174 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21175 	 * so disable MDT otherwise.  The checks are done here
21176 	 * and in tcp_wput_data().
21177 	 */
21178 	if (tcp->tcp_mdt &&
21179 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21180 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21181 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21182 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21183 		tcp->tcp_mdt = B_FALSE;
21184 
21185 	if (tcp->tcp_mdt) {
21186 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21187 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21188 			    "version (%d), expected version is %d",
21189 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21190 			tcp->tcp_mdt = B_FALSE;
21191 			return;
21192 		}
21193 
21194 		/*
21195 		 * We need the driver to be able to handle at least three
21196 		 * spans per packet in order for tcp MDT to be utilized.
21197 		 * The first is for the header portion, while the rest are
21198 		 * needed to handle a packet that straddles across two
21199 		 * virtually non-contiguous buffers; a typical tcp packet
21200 		 * therefore consists of only two spans.  Note that we take
21201 		 * a zero as "don't care".
21202 		 */
21203 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21204 		    mdt_capab->ill_mdt_span_limit < 3) {
21205 			tcp->tcp_mdt = B_FALSE;
21206 			return;
21207 		}
21208 
21209 		/* a zero means driver wants default value */
21210 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21211 		    tcps->tcps_mdt_max_pbufs);
21212 		if (tcp->tcp_mdt_max_pld == 0)
21213 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21214 
21215 		/* ensure 32-bit alignment */
21216 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21217 		    mdt_capab->ill_mdt_hdr_head), 4);
21218 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21219 		    mdt_capab->ill_mdt_hdr_tail), 4);
21220 
21221 		if (!first && !prev_state) {
21222 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21223 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21224 			    (void *)tcp->tcp_connp));
21225 		}
21226 	}
21227 }
21228 
21229 /* Unlink and return any mblk that looks like it contains a LSO info */
21230 static mblk_t *
21231 tcp_lso_info_mp(mblk_t *mp)
21232 {
21233 	mblk_t	*prev_mp;
21234 
21235 	for (;;) {
21236 		prev_mp = mp;
21237 		/* no more to process? */
21238 		if ((mp = mp->b_cont) == NULL)
21239 			break;
21240 
21241 		switch (DB_TYPE(mp)) {
21242 		case M_CTL:
21243 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21244 				continue;
21245 			ASSERT(prev_mp != NULL);
21246 			prev_mp->b_cont = mp->b_cont;
21247 			mp->b_cont = NULL;
21248 			return (mp);
21249 		default:
21250 			break;
21251 		}
21252 	}
21253 
21254 	return (mp);
21255 }
21256 
21257 /* LSO info update routine, called when IP notifies us about LSO */
21258 static void
21259 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21260 {
21261 	tcp_stack_t *tcps = tcp->tcp_tcps;
21262 
21263 	/*
21264 	 * IP is telling us to abort LSO on this connection?  We know
21265 	 * this because the capability is only turned off when IP
21266 	 * encounters some pathological cases, e.g. link-layer change
21267 	 * where the new NIC/driver doesn't support LSO, or in situation
21268 	 * where LSO usage on the link-layer has been switched off.
21269 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21270 	 * if the link-layer doesn't support LSO, and if it does, it
21271 	 * will indicate that the feature is to be turned on.
21272 	 */
21273 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21274 	TCP_STAT(tcps, tcp_lso_enabled);
21275 
21276 	/*
21277 	 * We currently only support LSO on simple TCP/IPv4,
21278 	 * so disable LSO otherwise.  The checks are done here
21279 	 * and in tcp_wput_data().
21280 	 */
21281 	if (tcp->tcp_lso &&
21282 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21283 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21284 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21285 		tcp->tcp_lso = B_FALSE;
21286 		TCP_STAT(tcps, tcp_lso_disabled);
21287 	} else {
21288 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21289 		    lso_capab->ill_lso_max);
21290 	}
21291 }
21292 
21293 static void
21294 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21295 {
21296 	conn_t *connp = tcp->tcp_connp;
21297 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21298 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21299 
21300 	ASSERT(ire != NULL);
21301 
21302 	/*
21303 	 * We may be in the fastpath here, and although we essentially do
21304 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21305 	 * we try to keep things as brief as possible.  After all, these
21306 	 * are only best-effort checks, and we do more thorough ones prior
21307 	 * to calling tcp_send()/tcp_multisend().
21308 	 */
21309 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21310 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21311 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21312 	    !(ire->ire_flags & RTF_MULTIRT) &&
21313 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21314 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21315 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21316 			/* Cache the result */
21317 			connp->conn_lso_ok = B_TRUE;
21318 
21319 			ASSERT(ill->ill_lso_capab != NULL);
21320 			if (!ill->ill_lso_capab->ill_lso_on) {
21321 				ill->ill_lso_capab->ill_lso_on = 1;
21322 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21323 				    "LSO for interface %s\n", (void *)connp,
21324 				    ill->ill_name));
21325 			}
21326 			tcp_lso_update(tcp, ill->ill_lso_capab);
21327 		} else if (ipst->ips_ip_multidata_outbound &&
21328 		    ILL_MDT_CAPABLE(ill)) {
21329 			/* Cache the result */
21330 			connp->conn_mdt_ok = B_TRUE;
21331 
21332 			ASSERT(ill->ill_mdt_capab != NULL);
21333 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21334 				ill->ill_mdt_capab->ill_mdt_on = 1;
21335 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21336 				    "MDT for interface %s\n", (void *)connp,
21337 				    ill->ill_name));
21338 			}
21339 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21340 		}
21341 	}
21342 
21343 	/*
21344 	 * The goal is to reduce the number of generated tcp segments by
21345 	 * setting the maxpsz multiplier to 0; this will have an affect on
21346 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21347 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21348 	 * of outbound segments and incoming ACKs, thus allowing for better
21349 	 * network and system performance.  In contrast the legacy behavior
21350 	 * may result in sending less than SMSS size, because the last mblk
21351 	 * for some packets may have more data than needed to make up SMSS,
21352 	 * and the legacy code refused to "split" it.
21353 	 *
21354 	 * We apply the new behavior on following situations:
21355 	 *
21356 	 *   1) Loopback connections,
21357 	 *   2) Connections in which the remote peer is not on local subnet,
21358 	 *   3) Local subnet connections over the bge interface (see below).
21359 	 *
21360 	 * Ideally, we would like this behavior to apply for interfaces other
21361 	 * than bge.  However, doing so would negatively impact drivers which
21362 	 * perform dynamic mapping and unmapping of DMA resources, which are
21363 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21364 	 * packet will be generated by tcp).  The bge driver does not suffer
21365 	 * from this, as it copies the mblks into pre-mapped buffers, and
21366 	 * therefore does not require more I/O resources than before.
21367 	 *
21368 	 * Otherwise, this behavior is present on all network interfaces when
21369 	 * the destination endpoint is non-local, since reducing the number
21370 	 * of packets in general is good for the network.
21371 	 *
21372 	 * TODO We need to remove this hard-coded conditional for bge once
21373 	 *	a better "self-tuning" mechanism, or a way to comprehend
21374 	 *	the driver transmit strategy is devised.  Until the solution
21375 	 *	is found and well understood, we live with this hack.
21376 	 */
21377 	if (!tcp_static_maxpsz &&
21378 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21379 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21380 		/* override the default value */
21381 		tcp->tcp_maxpsz = 0;
21382 
21383 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21384 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21385 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21386 	}
21387 
21388 	/* set the stream head parameters accordingly */
21389 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21390 }
21391 
21392 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21393 static void
21394 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21395 {
21396 	uchar_t	fval = *mp->b_rptr;
21397 	mblk_t	*tail;
21398 	queue_t	*q = tcp->tcp_wq;
21399 
21400 	/* TODO: How should flush interact with urgent data? */
21401 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21402 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21403 		/*
21404 		 * Flush only data that has not yet been put on the wire.  If
21405 		 * we flush data that we have already transmitted, life, as we
21406 		 * know it, may come to an end.
21407 		 */
21408 		tail = tcp->tcp_xmit_tail;
21409 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21410 		tcp->tcp_xmit_tail_unsent = 0;
21411 		tcp->tcp_unsent = 0;
21412 		if (tail->b_wptr != tail->b_rptr)
21413 			tail = tail->b_cont;
21414 		if (tail) {
21415 			mblk_t **excess = &tcp->tcp_xmit_head;
21416 			for (;;) {
21417 				mblk_t *mp1 = *excess;
21418 				if (mp1 == tail)
21419 					break;
21420 				tcp->tcp_xmit_tail = mp1;
21421 				tcp->tcp_xmit_last = mp1;
21422 				excess = &mp1->b_cont;
21423 			}
21424 			*excess = NULL;
21425 			tcp_close_mpp(&tail);
21426 			if (tcp->tcp_snd_zcopy_aware)
21427 				tcp_zcopy_notify(tcp);
21428 		}
21429 		/*
21430 		 * We have no unsent data, so unsent must be less than
21431 		 * tcp_xmit_lowater, so re-enable flow.
21432 		 */
21433 		mutex_enter(&tcp->tcp_non_sq_lock);
21434 		if (tcp->tcp_flow_stopped) {
21435 			tcp_clrqfull(tcp);
21436 		}
21437 		mutex_exit(&tcp->tcp_non_sq_lock);
21438 	}
21439 	/*
21440 	 * TODO: you can't just flush these, you have to increase rwnd for one
21441 	 * thing.  For another, how should urgent data interact?
21442 	 */
21443 	if (fval & FLUSHR) {
21444 		*mp->b_rptr = fval & ~FLUSHW;
21445 		/* XXX */
21446 		qreply(q, mp);
21447 		return;
21448 	}
21449 	freemsg(mp);
21450 }
21451 
21452 /*
21453  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21454  * messages.
21455  */
21456 static void
21457 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21458 {
21459 	mblk_t	*mp1;
21460 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
21461 	STRUCT_HANDLE(strbuf, sb);
21462 	queue_t *q = tcp->tcp_wq;
21463 	int	error;
21464 	uint_t	addrlen;
21465 
21466 	/* Make sure it is one of ours. */
21467 	switch (iocp->ioc_cmd) {
21468 	case TI_GETMYNAME:
21469 	case TI_GETPEERNAME:
21470 		break;
21471 	default:
21472 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21473 		return;
21474 	}
21475 	switch (mi_copy_state(q, mp, &mp1)) {
21476 	case -1:
21477 		return;
21478 	case MI_COPY_CASE(MI_COPY_IN, 1):
21479 		break;
21480 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21481 		/* Copy out the strbuf. */
21482 		mi_copyout(q, mp);
21483 		return;
21484 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21485 		/* All done. */
21486 		mi_copy_done(q, mp, 0);
21487 		return;
21488 	default:
21489 		mi_copy_done(q, mp, EPROTO);
21490 		return;
21491 	}
21492 	/* Check alignment of the strbuf */
21493 	if (!OK_32PTR(mp1->b_rptr)) {
21494 		mi_copy_done(q, mp, EINVAL);
21495 		return;
21496 	}
21497 
21498 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
21499 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21500 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21501 		mi_copy_done(q, mp, EINVAL);
21502 		return;
21503 	}
21504 
21505 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21506 	if (mp1 == NULL)
21507 		return;
21508 
21509 	switch (iocp->ioc_cmd) {
21510 	case TI_GETMYNAME:
21511 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
21512 		break;
21513 	case TI_GETPEERNAME:
21514 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
21515 		break;
21516 	}
21517 
21518 	if (error != 0) {
21519 		mi_copy_done(q, mp, error);
21520 	} else {
21521 		mp1->b_wptr += addrlen;
21522 		STRUCT_FSET(sb, len, addrlen);
21523 
21524 		/* Copy out the address */
21525 		mi_copyout(q, mp);
21526 	}
21527 }
21528 
21529 static void
21530 tcp_use_pure_tpi(tcp_t *tcp)
21531 {
21532 #ifdef	_ILP32
21533 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
21534 #else
21535 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21536 #endif
21537 	/*
21538 	 * Insert this socket into the acceptor hash.
21539 	 * We might need it for T_CONN_RES message
21540 	 */
21541 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21542 
21543 	tcp->tcp_issocket = B_FALSE;
21544 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
21545 }
21546 
21547 /*
21548  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21549  * messages.
21550  */
21551 /* ARGSUSED */
21552 static void
21553 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21554 {
21555 	conn_t 	*connp = (conn_t *)arg;
21556 	tcp_t	*tcp = connp->conn_tcp;
21557 	queue_t	*q = tcp->tcp_wq;
21558 	struct iocblk	*iocp;
21559 
21560 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21561 	/*
21562 	 * Try and ASSERT the minimum possible references on the
21563 	 * conn early enough. Since we are executing on write side,
21564 	 * the connection is obviously not detached and that means
21565 	 * there is a ref each for TCP and IP. Since we are behind
21566 	 * the squeue, the minimum references needed are 3. If the
21567 	 * conn is in classifier hash list, there should be an
21568 	 * extra ref for that (we check both the possibilities).
21569 	 */
21570 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21571 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21572 
21573 	iocp = (struct iocblk *)mp->b_rptr;
21574 	switch (iocp->ioc_cmd) {
21575 	case TCP_IOC_DEFAULT_Q:
21576 		/* Wants to be the default wq. */
21577 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21578 			iocp->ioc_error = EPERM;
21579 			iocp->ioc_count = 0;
21580 			mp->b_datap->db_type = M_IOCACK;
21581 			qreply(q, mp);
21582 			return;
21583 		}
21584 		tcp_def_q_set(tcp, mp);
21585 		return;
21586 	case _SIOCSOCKFALLBACK:
21587 		/*
21588 		 * Either sockmod is about to be popped and the socket
21589 		 * would now be treated as a plain stream, or a module
21590 		 * is about to be pushed so we could no longer use read-
21591 		 * side synchronous streams for fused loopback tcp.
21592 		 * Drain any queued data and disable direct sockfs
21593 		 * interface from now on.
21594 		 */
21595 		if (!tcp->tcp_issocket) {
21596 			DB_TYPE(mp) = M_IOCNAK;
21597 			iocp->ioc_error = EINVAL;
21598 		} else {
21599 			tcp_use_pure_tpi(tcp);
21600 			DB_TYPE(mp) = M_IOCACK;
21601 			iocp->ioc_error = 0;
21602 		}
21603 		iocp->ioc_count = 0;
21604 		iocp->ioc_rval = 0;
21605 		qreply(q, mp);
21606 		return;
21607 	}
21608 	CALL_IP_WPUT(connp, q, mp);
21609 }
21610 
21611 /*
21612  * This routine is called by tcp_wput() to handle all TPI requests.
21613  */
21614 /* ARGSUSED */
21615 static void
21616 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21617 {
21618 	conn_t 	*connp = (conn_t *)arg;
21619 	tcp_t	*tcp = connp->conn_tcp;
21620 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21621 	uchar_t *rptr;
21622 	t_scalar_t type;
21623 	cred_t *cr;
21624 
21625 	/*
21626 	 * Try and ASSERT the minimum possible references on the
21627 	 * conn early enough. Since we are executing on write side,
21628 	 * the connection is obviously not detached and that means
21629 	 * there is a ref each for TCP and IP. Since we are behind
21630 	 * the squeue, the minimum references needed are 3. If the
21631 	 * conn is in classifier hash list, there should be an
21632 	 * extra ref for that (we check both the possibilities).
21633 	 */
21634 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21635 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21636 
21637 	rptr = mp->b_rptr;
21638 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21639 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21640 		type = ((union T_primitives *)rptr)->type;
21641 		if (type == T_EXDATA_REQ) {
21642 			tcp_output_urgent(connp, mp, arg2);
21643 		} else if (type != T_DATA_REQ) {
21644 			goto non_urgent_data;
21645 		} else {
21646 			/* TODO: options, flags, ... from user */
21647 			/* Set length to zero for reclamation below */
21648 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21649 			freeb(mp);
21650 		}
21651 		return;
21652 	} else {
21653 		if (tcp->tcp_debug) {
21654 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21655 			    "tcp_wput_proto, dropping one...");
21656 		}
21657 		freemsg(mp);
21658 		return;
21659 	}
21660 
21661 non_urgent_data:
21662 
21663 	switch ((int)tprim->type) {
21664 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21665 		/*
21666 		 * save the kssl_ent_t from the next block, and convert this
21667 		 * back to a normal bind_req.
21668 		 */
21669 		if (mp->b_cont != NULL) {
21670 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21671 
21672 			if (tcp->tcp_kssl_ent != NULL) {
21673 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21674 				    KSSL_NO_PROXY);
21675 				tcp->tcp_kssl_ent = NULL;
21676 			}
21677 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21678 			    sizeof (kssl_ent_t));
21679 			kssl_hold_ent(tcp->tcp_kssl_ent);
21680 			freemsg(mp->b_cont);
21681 			mp->b_cont = NULL;
21682 		}
21683 		tprim->type = T_BIND_REQ;
21684 
21685 	/* FALLTHROUGH */
21686 	case O_T_BIND_REQ:	/* bind request */
21687 	case T_BIND_REQ:	/* new semantics bind request */
21688 		tcp_tpi_bind(tcp, mp);
21689 		break;
21690 	case T_UNBIND_REQ:	/* unbind request */
21691 		tcp_tpi_unbind(tcp, mp);
21692 		break;
21693 	case O_T_CONN_RES:	/* old connection response XXX */
21694 	case T_CONN_RES:	/* connection response */
21695 		tcp_tli_accept(tcp, mp);
21696 		break;
21697 	case T_CONN_REQ:	/* connection request */
21698 		tcp_tpi_connect(tcp, mp);
21699 		break;
21700 	case T_DISCON_REQ:	/* disconnect request */
21701 		tcp_disconnect(tcp, mp);
21702 		break;
21703 	case T_CAPABILITY_REQ:
21704 		tcp_capability_req(tcp, mp);	/* capability request */
21705 		break;
21706 	case T_INFO_REQ:	/* information request */
21707 		tcp_info_req(tcp, mp);
21708 		break;
21709 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21710 	case T_OPTMGMT_REQ:
21711 		/*
21712 		 * Note:  no support for snmpcom_req() through new
21713 		 * T_OPTMGMT_REQ. See comments in ip.c
21714 		 */
21715 
21716 		/*
21717 		 * All Solaris components should pass a db_credp
21718 		 * for this TPI message, hence we ASSERT.
21719 		 * But in case there is some other M_PROTO that looks
21720 		 * like a TPI message sent by some other kernel
21721 		 * component, we check and return an error.
21722 		 */
21723 		cr = msg_getcred(mp, NULL);
21724 		ASSERT(cr != NULL);
21725 		if (cr == NULL) {
21726 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
21727 			return;
21728 		}
21729 		/*
21730 		 * If EINPROGRESS is returned, the request has been queued
21731 		 * for subsequent processing by ip_restart_optmgmt(), which
21732 		 * will do the CONN_DEC_REF().
21733 		 */
21734 		CONN_INC_REF(connp);
21735 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
21736 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21737 			    B_TRUE) != EINPROGRESS) {
21738 				CONN_DEC_REF(connp);
21739 			}
21740 		} else {
21741 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21742 			    B_TRUE) != EINPROGRESS) {
21743 				CONN_DEC_REF(connp);
21744 			}
21745 		}
21746 		break;
21747 
21748 	case T_UNITDATA_REQ:	/* unitdata request */
21749 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21750 		break;
21751 	case T_ORDREL_REQ:	/* orderly release req */
21752 		freemsg(mp);
21753 
21754 		if (tcp->tcp_fused)
21755 			tcp_unfuse(tcp);
21756 
21757 		if (tcp_xmit_end(tcp) != 0) {
21758 			/*
21759 			 * We were crossing FINs and got a reset from
21760 			 * the other side. Just ignore it.
21761 			 */
21762 			if (tcp->tcp_debug) {
21763 				(void) strlog(TCP_MOD_ID, 0, 1,
21764 				    SL_ERROR|SL_TRACE,
21765 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21766 				    "state %s",
21767 				    tcp_display(tcp, NULL,
21768 				    DISP_ADDR_AND_PORT));
21769 			}
21770 		}
21771 		break;
21772 	case T_ADDR_REQ:
21773 		tcp_addr_req(tcp, mp);
21774 		break;
21775 	default:
21776 		if (tcp->tcp_debug) {
21777 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21778 			    "tcp_wput_proto, bogus TPI msg, type %d",
21779 			    tprim->type);
21780 		}
21781 		/*
21782 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21783 		 * to recover.
21784 		 */
21785 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21786 		break;
21787 	}
21788 }
21789 
21790 /*
21791  * The TCP write service routine should never be called...
21792  */
21793 /* ARGSUSED */
21794 static void
21795 tcp_wsrv(queue_t *q)
21796 {
21797 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
21798 
21799 	TCP_STAT(tcps, tcp_wsrv_called);
21800 }
21801 
21802 /* Non overlapping byte exchanger */
21803 static void
21804 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21805 {
21806 	uchar_t	uch;
21807 
21808 	while (len-- > 0) {
21809 		uch = a[len];
21810 		a[len] = b[len];
21811 		b[len] = uch;
21812 	}
21813 }
21814 
21815 /*
21816  * Send out a control packet on the tcp connection specified.  This routine
21817  * is typically called where we need a simple ACK or RST generated.
21818  */
21819 static void
21820 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21821 {
21822 	uchar_t		*rptr;
21823 	tcph_t		*tcph;
21824 	ipha_t		*ipha = NULL;
21825 	ip6_t		*ip6h = NULL;
21826 	uint32_t	sum;
21827 	int		tcp_hdr_len;
21828 	int		tcp_ip_hdr_len;
21829 	mblk_t		*mp;
21830 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21831 
21832 	/*
21833 	 * Save sum for use in source route later.
21834 	 */
21835 	ASSERT(tcp != NULL);
21836 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21837 	tcp_hdr_len = tcp->tcp_hdr_len;
21838 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21839 
21840 	/* If a text string is passed in with the request, pass it to strlog. */
21841 	if (str != NULL && tcp->tcp_debug) {
21842 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21843 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21844 		    str, seq, ack, ctl);
21845 	}
21846 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
21847 	    BPRI_MED);
21848 	if (mp == NULL) {
21849 		return;
21850 	}
21851 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
21852 	mp->b_rptr = rptr;
21853 	mp->b_wptr = &rptr[tcp_hdr_len];
21854 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21855 
21856 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21857 		ipha = (ipha_t *)rptr;
21858 		ipha->ipha_length = htons(tcp_hdr_len);
21859 	} else {
21860 		ip6h = (ip6_t *)rptr;
21861 		ASSERT(tcp != NULL);
21862 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21863 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21864 	}
21865 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21866 	tcph->th_flags[0] = (uint8_t)ctl;
21867 	if (ctl & TH_RST) {
21868 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
21869 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
21870 		/*
21871 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21872 		 */
21873 		if (tcp->tcp_snd_ts_ok &&
21874 		    tcp->tcp_state > TCPS_SYN_SENT) {
21875 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21876 			*(mp->b_wptr) = TCPOPT_EOL;
21877 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21878 				ipha->ipha_length = htons(tcp_hdr_len -
21879 				    TCPOPT_REAL_TS_LEN);
21880 			} else {
21881 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21882 				    TCPOPT_REAL_TS_LEN);
21883 			}
21884 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21885 			sum -= TCPOPT_REAL_TS_LEN;
21886 		}
21887 	}
21888 	if (ctl & TH_ACK) {
21889 		if (tcp->tcp_snd_ts_ok) {
21890 			U32_TO_BE32(lbolt,
21891 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21892 			U32_TO_BE32(tcp->tcp_ts_recent,
21893 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21894 		}
21895 
21896 		/* Update the latest receive window size in TCP header. */
21897 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21898 		    tcph->th_win);
21899 		tcp->tcp_rack = ack;
21900 		tcp->tcp_rack_cnt = 0;
21901 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
21902 	}
21903 	BUMP_LOCAL(tcp->tcp_obsegs);
21904 	U32_TO_BE32(seq, tcph->th_seq);
21905 	U32_TO_BE32(ack, tcph->th_ack);
21906 	/*
21907 	 * Include the adjustment for a source route if any.
21908 	 */
21909 	sum = (sum >> 16) + (sum & 0xFFFF);
21910 	U16_TO_BE16(sum, tcph->th_sum);
21911 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21912 }
21913 
21914 /*
21915  * If this routine returns B_TRUE, TCP can generate a RST in response
21916  * to a segment.  If it returns B_FALSE, TCP should not respond.
21917  */
21918 static boolean_t
21919 tcp_send_rst_chk(tcp_stack_t *tcps)
21920 {
21921 	clock_t	now;
21922 
21923 	/*
21924 	 * TCP needs to protect itself from generating too many RSTs.
21925 	 * This can be a DoS attack by sending us random segments
21926 	 * soliciting RSTs.
21927 	 *
21928 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21929 	 * in each 1 second interval.  In this way, TCP still generate
21930 	 * RSTs in normal cases but when under attack, the impact is
21931 	 * limited.
21932 	 */
21933 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
21934 		now = lbolt;
21935 		/* lbolt can wrap around. */
21936 		if ((tcps->tcps_last_rst_intrvl > now) ||
21937 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
21938 		    1*SECONDS)) {
21939 			tcps->tcps_last_rst_intrvl = now;
21940 			tcps->tcps_rst_cnt = 1;
21941 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
21942 			return (B_FALSE);
21943 		}
21944 	}
21945 	return (B_TRUE);
21946 }
21947 
21948 /*
21949  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21950  */
21951 static void
21952 tcp_ip_ire_mark_advice(tcp_t *tcp)
21953 {
21954 	mblk_t *mp;
21955 	ipic_t *ipic;
21956 
21957 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21958 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21959 		    &ipic);
21960 	} else {
21961 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21962 		    &ipic);
21963 	}
21964 	if (mp == NULL)
21965 		return;
21966 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21967 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21968 }
21969 
21970 /*
21971  * Return an IP advice ioctl mblk and set ipic to be the pointer
21972  * to the advice structure.
21973  */
21974 static mblk_t *
21975 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21976 {
21977 	struct iocblk *ioc;
21978 	mblk_t *mp, *mp1;
21979 
21980 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21981 	if (mp == NULL)
21982 		return (NULL);
21983 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21984 	*ipic = (ipic_t *)mp->b_rptr;
21985 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21986 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21987 
21988 	bcopy(addr, *ipic + 1, addr_len);
21989 
21990 	(*ipic)->ipic_addr_length = addr_len;
21991 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21992 
21993 	mp1 = mkiocb(IP_IOCTL);
21994 	if (mp1 == NULL) {
21995 		freemsg(mp);
21996 		return (NULL);
21997 	}
21998 	mp1->b_cont = mp;
21999 	ioc = (struct iocblk *)mp1->b_rptr;
22000 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22001 
22002 	return (mp1);
22003 }
22004 
22005 /*
22006  * Generate a reset based on an inbound packet, connp is set by caller
22007  * when RST is in response to an unexpected inbound packet for which
22008  * there is active tcp state in the system.
22009  *
22010  * IPSEC NOTE : Try to send the reply with the same protection as it came
22011  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22012  * the packet will go out at the same level of protection as it came in by
22013  * converting the IPSEC_IN to IPSEC_OUT.
22014  */
22015 static void
22016 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22017     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22018     tcp_stack_t *tcps, conn_t *connp)
22019 {
22020 	ipha_t		*ipha = NULL;
22021 	ip6_t		*ip6h = NULL;
22022 	ushort_t	len;
22023 	tcph_t		*tcph;
22024 	int		i;
22025 	mblk_t		*ipsec_mp;
22026 	boolean_t	mctl_present;
22027 	ipic_t		*ipic;
22028 	ipaddr_t	v4addr;
22029 	in6_addr_t	v6addr;
22030 	int		addr_len;
22031 	void		*addr;
22032 	queue_t		*q = tcps->tcps_g_q;
22033 	tcp_t		*tcp;
22034 	cred_t		*cr;
22035 	pid_t		pid;
22036 	mblk_t		*nmp;
22037 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22038 
22039 	if (tcps->tcps_g_q == NULL) {
22040 		/*
22041 		 * For non-zero stackids the default queue isn't created
22042 		 * until the first open, thus there can be a need to send
22043 		 * a reset before then. But we can't do that, hence we just
22044 		 * drop the packet. Later during boot, when the default queue
22045 		 * has been setup, a retransmitted packet from the peer
22046 		 * will result in a reset.
22047 		 */
22048 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22049 		    GLOBAL_NETSTACKID);
22050 		freemsg(mp);
22051 		return;
22052 	}
22053 
22054 	if (connp != NULL)
22055 		tcp = connp->conn_tcp;
22056 	else
22057 		tcp = Q_TO_TCP(q);
22058 
22059 	if (!tcp_send_rst_chk(tcps)) {
22060 		tcps->tcps_rst_unsent++;
22061 		freemsg(mp);
22062 		return;
22063 	}
22064 
22065 	if (mp->b_datap->db_type == M_CTL) {
22066 		ipsec_mp = mp;
22067 		mp = mp->b_cont;
22068 		mctl_present = B_TRUE;
22069 	} else {
22070 		ipsec_mp = mp;
22071 		mctl_present = B_FALSE;
22072 	}
22073 
22074 	if (str && q && tcps->tcps_dbg) {
22075 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22076 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22077 		    "flags 0x%x",
22078 		    str, seq, ack, ctl);
22079 	}
22080 	if (mp->b_datap->db_ref != 1) {
22081 		mblk_t *mp1 = copyb(mp);
22082 		freemsg(mp);
22083 		mp = mp1;
22084 		if (!mp) {
22085 			if (mctl_present)
22086 				freeb(ipsec_mp);
22087 			return;
22088 		} else {
22089 			if (mctl_present) {
22090 				ipsec_mp->b_cont = mp;
22091 			} else {
22092 				ipsec_mp = mp;
22093 			}
22094 		}
22095 	} else if (mp->b_cont) {
22096 		freemsg(mp->b_cont);
22097 		mp->b_cont = NULL;
22098 	}
22099 	/*
22100 	 * We skip reversing source route here.
22101 	 * (for now we replace all IP options with EOL)
22102 	 */
22103 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22104 		ipha = (ipha_t *)mp->b_rptr;
22105 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22106 			mp->b_rptr[i] = IPOPT_EOL;
22107 		/*
22108 		 * Make sure that src address isn't flagrantly invalid.
22109 		 * Not all broadcast address checking for the src address
22110 		 * is possible, since we don't know the netmask of the src
22111 		 * addr.  No check for destination address is done, since
22112 		 * IP will not pass up a packet with a broadcast dest
22113 		 * address to TCP.  Similar checks are done below for IPv6.
22114 		 */
22115 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22116 		    CLASSD(ipha->ipha_src)) {
22117 			freemsg(ipsec_mp);
22118 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22119 			return;
22120 		}
22121 	} else {
22122 		ip6h = (ip6_t *)mp->b_rptr;
22123 
22124 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22125 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22126 			freemsg(ipsec_mp);
22127 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22128 			return;
22129 		}
22130 
22131 		/* Remove any extension headers assuming partial overlay */
22132 		if (ip_hdr_len > IPV6_HDR_LEN) {
22133 			uint8_t *to;
22134 
22135 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22136 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22137 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22138 			ip_hdr_len = IPV6_HDR_LEN;
22139 			ip6h = (ip6_t *)mp->b_rptr;
22140 			ip6h->ip6_nxt = IPPROTO_TCP;
22141 		}
22142 	}
22143 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22144 	if (tcph->th_flags[0] & TH_RST) {
22145 		freemsg(ipsec_mp);
22146 		return;
22147 	}
22148 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22149 	len = ip_hdr_len + sizeof (tcph_t);
22150 	mp->b_wptr = &mp->b_rptr[len];
22151 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22152 		ipha->ipha_length = htons(len);
22153 		/* Swap addresses */
22154 		v4addr = ipha->ipha_src;
22155 		ipha->ipha_src = ipha->ipha_dst;
22156 		ipha->ipha_dst = v4addr;
22157 		ipha->ipha_ident = 0;
22158 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22159 		addr_len = IP_ADDR_LEN;
22160 		addr = &v4addr;
22161 	} else {
22162 		/* No ip6i_t in this case */
22163 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22164 		/* Swap addresses */
22165 		v6addr = ip6h->ip6_src;
22166 		ip6h->ip6_src = ip6h->ip6_dst;
22167 		ip6h->ip6_dst = v6addr;
22168 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22169 		addr_len = IPV6_ADDR_LEN;
22170 		addr = &v6addr;
22171 	}
22172 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22173 	U32_TO_BE32(ack, tcph->th_ack);
22174 	U32_TO_BE32(seq, tcph->th_seq);
22175 	U16_TO_BE16(0, tcph->th_win);
22176 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22177 	tcph->th_flags[0] = (uint8_t)ctl;
22178 	if (ctl & TH_RST) {
22179 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22180 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22181 	}
22182 
22183 	/* IP trusts us to set up labels when required. */
22184 	if (is_system_labeled() && (cr = msg_getcred(mp, &pid)) != NULL &&
22185 	    crgetlabel(cr) != NULL) {
22186 		int err;
22187 
22188 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22189 			err = tsol_check_label(cr, &mp,
22190 			    tcp->tcp_connp->conn_mac_exempt,
22191 			    tcps->tcps_netstack->netstack_ip, pid);
22192 		else
22193 			err = tsol_check_label_v6(cr, &mp,
22194 			    tcp->tcp_connp->conn_mac_exempt,
22195 			    tcps->tcps_netstack->netstack_ip, pid);
22196 		if (mctl_present)
22197 			ipsec_mp->b_cont = mp;
22198 		else
22199 			ipsec_mp = mp;
22200 		if (err != 0) {
22201 			freemsg(ipsec_mp);
22202 			return;
22203 		}
22204 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22205 			ipha = (ipha_t *)mp->b_rptr;
22206 		} else {
22207 			ip6h = (ip6_t *)mp->b_rptr;
22208 		}
22209 	}
22210 
22211 	if (mctl_present) {
22212 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22213 
22214 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22215 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22216 			return;
22217 		}
22218 	}
22219 	if (zoneid == ALL_ZONES)
22220 		zoneid = GLOBAL_ZONEID;
22221 
22222 	/* Add the zoneid so ip_output routes it properly */
22223 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22224 		freemsg(ipsec_mp);
22225 		return;
22226 	}
22227 	ipsec_mp = nmp;
22228 
22229 	/*
22230 	 * NOTE:  one might consider tracing a TCP packet here, but
22231 	 * this function has no active TCP state and no tcp structure
22232 	 * that has a trace buffer.  If we traced here, we would have
22233 	 * to keep a local trace buffer in tcp_record_trace().
22234 	 *
22235 	 * TSol note: The mblk that contains the incoming packet was
22236 	 * reused by tcp_xmit_listener_reset, so it already contains
22237 	 * the right credentials and we don't need to call mblk_setcred.
22238 	 * Also the conn's cred is not right since it is associated
22239 	 * with tcps_g_q.
22240 	 */
22241 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22242 
22243 	/*
22244 	 * Tell IP to mark the IRE used for this destination temporary.
22245 	 * This way, we can limit our exposure to DoS attack because IP
22246 	 * creates an IRE for each destination.  If there are too many,
22247 	 * the time to do any routing lookup will be extremely long.  And
22248 	 * the lookup can be in interrupt context.
22249 	 *
22250 	 * Note that in normal circumstances, this marking should not
22251 	 * affect anything.  It would be nice if only 1 message is
22252 	 * needed to inform IP that the IRE created for this RST should
22253 	 * not be added to the cache table.  But there is currently
22254 	 * not such communication mechanism between TCP and IP.  So
22255 	 * the best we can do now is to send the advice ioctl to IP
22256 	 * to mark the IRE temporary.
22257 	 */
22258 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22259 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22260 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22261 	}
22262 }
22263 
22264 /*
22265  * Initiate closedown sequence on an active connection.  (May be called as
22266  * writer.)  Return value zero for OK return, non-zero for error return.
22267  */
22268 static int
22269 tcp_xmit_end(tcp_t *tcp)
22270 {
22271 	ipic_t	*ipic;
22272 	mblk_t	*mp;
22273 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22274 
22275 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22276 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22277 		/*
22278 		 * Invalid state, only states TCPS_SYN_RCVD,
22279 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22280 		 */
22281 		return (-1);
22282 	}
22283 
22284 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22285 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22286 	/*
22287 	 * If there is nothing more unsent, send the FIN now.
22288 	 * Otherwise, it will go out with the last segment.
22289 	 */
22290 	if (tcp->tcp_unsent == 0) {
22291 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22292 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22293 
22294 		if (mp) {
22295 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22296 		} else {
22297 			/*
22298 			 * Couldn't allocate msg.  Pretend we got it out.
22299 			 * Wait for rexmit timeout.
22300 			 */
22301 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22302 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22303 		}
22304 
22305 		/*
22306 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22307 		 * changed.
22308 		 */
22309 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22310 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22311 		}
22312 	} else {
22313 		/*
22314 		 * If tcp->tcp_cork is set, then the data will not get sent,
22315 		 * so we have to check that and unset it first.
22316 		 */
22317 		if (tcp->tcp_cork)
22318 			tcp->tcp_cork = B_FALSE;
22319 		tcp_wput_data(tcp, NULL, B_FALSE);
22320 	}
22321 
22322 	/*
22323 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22324 	 * is 0, don't update the cache.
22325 	 */
22326 	if (tcps->tcps_rtt_updates == 0 ||
22327 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22328 		return (0);
22329 
22330 	/*
22331 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22332 	 * different from the destination.
22333 	 */
22334 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22335 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22336 			return (0);
22337 		}
22338 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22339 		    &ipic);
22340 	} else {
22341 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22342 		    &tcp->tcp_ip6h->ip6_dst))) {
22343 			return (0);
22344 		}
22345 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22346 		    &ipic);
22347 	}
22348 
22349 	/* Record route attributes in the IRE for use by future connections. */
22350 	if (mp == NULL)
22351 		return (0);
22352 
22353 	/*
22354 	 * We do not have a good algorithm to update ssthresh at this time.
22355 	 * So don't do any update.
22356 	 */
22357 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22358 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22359 
22360 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22361 
22362 	return (0);
22363 }
22364 
22365 /* ARGSUSED */
22366 void
22367 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
22368 {
22369 	conn_t *connp = (conn_t *)arg;
22370 	mblk_t *mp1;
22371 	tcp_t *tcp = connp->conn_tcp;
22372 	tcp_xmit_reset_event_t *eventp;
22373 
22374 	ASSERT(mp->b_datap->db_type == M_PROTO &&
22375 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
22376 
22377 	if (tcp->tcp_state != TCPS_LISTEN) {
22378 		freemsg(mp);
22379 		return;
22380 	}
22381 
22382 	mp1 = mp->b_cont;
22383 	mp->b_cont = NULL;
22384 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
22385 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
22386 	    connp->conn_netstack);
22387 
22388 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
22389 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
22390 	freemsg(mp);
22391 }
22392 
22393 /*
22394  * Generate a "no listener here" RST in response to an "unknown" segment.
22395  * connp is set by caller when RST is in response to an unexpected
22396  * inbound packet for which there is active tcp state in the system.
22397  * Note that we are reusing the incoming mp to construct the outgoing RST.
22398  */
22399 void
22400 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22401     tcp_stack_t *tcps, conn_t *connp)
22402 {
22403 	uchar_t		*rptr;
22404 	uint32_t	seg_len;
22405 	tcph_t		*tcph;
22406 	uint32_t	seg_seq;
22407 	uint32_t	seg_ack;
22408 	uint_t		flags;
22409 	mblk_t		*ipsec_mp;
22410 	ipha_t 		*ipha;
22411 	ip6_t 		*ip6h;
22412 	boolean_t	mctl_present = B_FALSE;
22413 	boolean_t	check = B_TRUE;
22414 	boolean_t	policy_present;
22415 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22416 
22417 	TCP_STAT(tcps, tcp_no_listener);
22418 
22419 	ipsec_mp = mp;
22420 
22421 	if (mp->b_datap->db_type == M_CTL) {
22422 		ipsec_in_t *ii;
22423 
22424 		mctl_present = B_TRUE;
22425 		mp = mp->b_cont;
22426 
22427 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22428 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22429 		if (ii->ipsec_in_dont_check) {
22430 			check = B_FALSE;
22431 			if (!ii->ipsec_in_secure) {
22432 				freeb(ipsec_mp);
22433 				mctl_present = B_FALSE;
22434 				ipsec_mp = mp;
22435 			}
22436 		}
22437 	}
22438 
22439 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22440 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22441 		ipha = (ipha_t *)mp->b_rptr;
22442 		ip6h = NULL;
22443 	} else {
22444 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22445 		ipha = NULL;
22446 		ip6h = (ip6_t *)mp->b_rptr;
22447 	}
22448 
22449 	if (check && policy_present) {
22450 		/*
22451 		 * The conn_t parameter is NULL because we already know
22452 		 * nobody's home.
22453 		 */
22454 		ipsec_mp = ipsec_check_global_policy(
22455 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22456 		    tcps->tcps_netstack);
22457 		if (ipsec_mp == NULL)
22458 			return;
22459 	}
22460 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22461 		DTRACE_PROBE2(
22462 		    tx__ip__log__error__nolistener__tcp,
22463 		    char *, "Could not reply with RST to mp(1)",
22464 		    mblk_t *, mp);
22465 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22466 		freemsg(ipsec_mp);
22467 		return;
22468 	}
22469 
22470 	rptr = mp->b_rptr;
22471 
22472 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22473 	seg_seq = BE32_TO_U32(tcph->th_seq);
22474 	seg_ack = BE32_TO_U32(tcph->th_ack);
22475 	flags = tcph->th_flags[0];
22476 
22477 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22478 	if (flags & TH_RST) {
22479 		freemsg(ipsec_mp);
22480 	} else if (flags & TH_ACK) {
22481 		tcp_xmit_early_reset("no tcp, reset",
22482 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22483 		    connp);
22484 	} else {
22485 		if (flags & TH_SYN) {
22486 			seg_len++;
22487 		} else {
22488 			/*
22489 			 * Here we violate the RFC.  Note that a normal
22490 			 * TCP will never send a segment without the ACK
22491 			 * flag, except for RST or SYN segment.  This
22492 			 * segment is neither.  Just drop it on the
22493 			 * floor.
22494 			 */
22495 			freemsg(ipsec_mp);
22496 			tcps->tcps_rst_unsent++;
22497 			return;
22498 		}
22499 
22500 		tcp_xmit_early_reset("no tcp, reset/ack",
22501 		    ipsec_mp, 0, seg_seq + seg_len,
22502 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22503 	}
22504 }
22505 
22506 /*
22507  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22508  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22509  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22510  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22511  * otherwise it will dup partial mblks.)
22512  * Otherwise, an appropriate ACK packet will be generated.  This
22513  * routine is not usually called to send new data for the first time.  It
22514  * is mostly called out of the timer for retransmits, and to generate ACKs.
22515  *
22516  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22517  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22518  * of the original mblk chain will be returned in *offset and *end_mp.
22519  */
22520 mblk_t *
22521 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22522     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22523     boolean_t rexmit)
22524 {
22525 	int	data_length;
22526 	int32_t	off = 0;
22527 	uint_t	flags;
22528 	mblk_t	*mp1;
22529 	mblk_t	*mp2;
22530 	uchar_t	*rptr;
22531 	tcph_t	*tcph;
22532 	int32_t	num_sack_blk = 0;
22533 	int32_t	sack_opt_len = 0;
22534 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22535 
22536 	/* Allocate for our maximum TCP header + link-level */
22537 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22538 	    tcps->tcps_wroff_xtra, BPRI_MED);
22539 	if (!mp1)
22540 		return (NULL);
22541 	data_length = 0;
22542 
22543 	/*
22544 	 * Note that tcp_mss has been adjusted to take into account the
22545 	 * timestamp option if applicable.  Because SACK options do not
22546 	 * appear in every TCP segments and they are of variable lengths,
22547 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22548 	 * the actual segment length when we need to send a segment which
22549 	 * includes SACK options.
22550 	 */
22551 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22552 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22553 		    tcp->tcp_num_sack_blk);
22554 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22555 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22556 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22557 			max_to_send -= sack_opt_len;
22558 	}
22559 
22560 	if (offset != NULL) {
22561 		off = *offset;
22562 		/* We use offset as an indicator that end_mp is not NULL. */
22563 		*end_mp = NULL;
22564 	}
22565 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22566 		/* This could be faster with cooperation from downstream */
22567 		if (mp2 != mp1 && !sendall &&
22568 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22569 		    max_to_send)
22570 			/*
22571 			 * Don't send the next mblk since the whole mblk
22572 			 * does not fit.
22573 			 */
22574 			break;
22575 		mp2->b_cont = dupb(mp);
22576 		mp2 = mp2->b_cont;
22577 		if (!mp2) {
22578 			freemsg(mp1);
22579 			return (NULL);
22580 		}
22581 		mp2->b_rptr += off;
22582 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22583 		    (uintptr_t)INT_MAX);
22584 
22585 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22586 		if (data_length > max_to_send) {
22587 			mp2->b_wptr -= data_length - max_to_send;
22588 			data_length = max_to_send;
22589 			off = mp2->b_wptr - mp->b_rptr;
22590 			break;
22591 		} else {
22592 			off = 0;
22593 		}
22594 	}
22595 	if (offset != NULL) {
22596 		*offset = off;
22597 		*end_mp = mp;
22598 	}
22599 	if (seg_len != NULL) {
22600 		*seg_len = data_length;
22601 	}
22602 
22603 	/* Update the latest receive window size in TCP header. */
22604 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22605 	    tcp->tcp_tcph->th_win);
22606 
22607 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22608 	mp1->b_rptr = rptr;
22609 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22610 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22611 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22612 	U32_TO_ABE32(seq, tcph->th_seq);
22613 
22614 	/*
22615 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22616 	 * that this function was called from tcp_wput_data. Thus, when called
22617 	 * to retransmit data the setting of the PUSH bit may appear some
22618 	 * what random in that it might get set when it should not. This
22619 	 * should not pose any performance issues.
22620 	 */
22621 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22622 	    tcp->tcp_unsent == data_length)) {
22623 		flags = TH_ACK | TH_PUSH;
22624 	} else {
22625 		flags = TH_ACK;
22626 	}
22627 
22628 	if (tcp->tcp_ecn_ok) {
22629 		if (tcp->tcp_ecn_echo_on)
22630 			flags |= TH_ECE;
22631 
22632 		/*
22633 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22634 		 * There is no TCP flow control for non-data segments, and
22635 		 * only data segment is transmitted reliably.
22636 		 */
22637 		if (data_length > 0 && !rexmit) {
22638 			SET_ECT(tcp, rptr);
22639 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22640 				flags |= TH_CWR;
22641 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22642 			}
22643 		}
22644 	}
22645 
22646 	if (tcp->tcp_valid_bits) {
22647 		uint32_t u1;
22648 
22649 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22650 		    seq == tcp->tcp_iss) {
22651 			uchar_t	*wptr;
22652 
22653 			/*
22654 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22655 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22656 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22657 			 * our SYN is not ack'ed but the app closes this
22658 			 * TCP connection.
22659 			 */
22660 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22661 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22662 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22663 
22664 			/*
22665 			 * Tack on the MSS option.  It is always needed
22666 			 * for both active and passive open.
22667 			 *
22668 			 * MSS option value should be interface MTU - MIN
22669 			 * TCP/IP header according to RFC 793 as it means
22670 			 * the maximum segment size TCP can receive.  But
22671 			 * to get around some broken middle boxes/end hosts
22672 			 * out there, we allow the option value to be the
22673 			 * same as the MSS option size on the peer side.
22674 			 * In this way, the other side will not send
22675 			 * anything larger than they can receive.
22676 			 *
22677 			 * Note that for SYN_SENT state, the ndd param
22678 			 * tcp_use_smss_as_mss_opt has no effect as we
22679 			 * don't know the peer's MSS option value. So
22680 			 * the only case we need to take care of is in
22681 			 * SYN_RCVD state, which is done later.
22682 			 */
22683 			wptr = mp1->b_wptr;
22684 			wptr[0] = TCPOPT_MAXSEG;
22685 			wptr[1] = TCPOPT_MAXSEG_LEN;
22686 			wptr += 2;
22687 			u1 = tcp->tcp_if_mtu -
22688 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22689 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22690 			    TCP_MIN_HEADER_LENGTH;
22691 			U16_TO_BE16(u1, wptr);
22692 			mp1->b_wptr = wptr + 2;
22693 			/* Update the offset to cover the additional word */
22694 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22695 
22696 			/*
22697 			 * Note that the following way of filling in
22698 			 * TCP options are not optimal.  Some NOPs can
22699 			 * be saved.  But there is no need at this time
22700 			 * to optimize it.  When it is needed, we will
22701 			 * do it.
22702 			 */
22703 			switch (tcp->tcp_state) {
22704 			case TCPS_SYN_SENT:
22705 				flags = TH_SYN;
22706 
22707 				if (tcp->tcp_snd_ts_ok) {
22708 					uint32_t llbolt = (uint32_t)lbolt;
22709 
22710 					wptr = mp1->b_wptr;
22711 					wptr[0] = TCPOPT_NOP;
22712 					wptr[1] = TCPOPT_NOP;
22713 					wptr[2] = TCPOPT_TSTAMP;
22714 					wptr[3] = TCPOPT_TSTAMP_LEN;
22715 					wptr += 4;
22716 					U32_TO_BE32(llbolt, wptr);
22717 					wptr += 4;
22718 					ASSERT(tcp->tcp_ts_recent == 0);
22719 					U32_TO_BE32(0L, wptr);
22720 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22721 					tcph->th_offset_and_rsrvd[0] +=
22722 					    (3 << 4);
22723 				}
22724 
22725 				/*
22726 				 * Set up all the bits to tell other side
22727 				 * we are ECN capable.
22728 				 */
22729 				if (tcp->tcp_ecn_ok) {
22730 					flags |= (TH_ECE | TH_CWR);
22731 				}
22732 				break;
22733 			case TCPS_SYN_RCVD:
22734 				flags |= TH_SYN;
22735 
22736 				/*
22737 				 * Reset the MSS option value to be SMSS
22738 				 * We should probably add back the bytes
22739 				 * for timestamp option and IPsec.  We
22740 				 * don't do that as this is a workaround
22741 				 * for broken middle boxes/end hosts, it
22742 				 * is better for us to be more cautious.
22743 				 * They may not take these things into
22744 				 * account in their SMSS calculation.  Thus
22745 				 * the peer's calculated SMSS may be smaller
22746 				 * than what it can be.  This should be OK.
22747 				 */
22748 				if (tcps->tcps_use_smss_as_mss_opt) {
22749 					u1 = tcp->tcp_mss;
22750 					U16_TO_BE16(u1, wptr);
22751 				}
22752 
22753 				/*
22754 				 * If the other side is ECN capable, reply
22755 				 * that we are also ECN capable.
22756 				 */
22757 				if (tcp->tcp_ecn_ok)
22758 					flags |= TH_ECE;
22759 				break;
22760 			default:
22761 				/*
22762 				 * The above ASSERT() makes sure that this
22763 				 * must be FIN-WAIT-1 state.  Our SYN has
22764 				 * not been ack'ed so retransmit it.
22765 				 */
22766 				flags |= TH_SYN;
22767 				break;
22768 			}
22769 
22770 			if (tcp->tcp_snd_ws_ok) {
22771 				wptr = mp1->b_wptr;
22772 				wptr[0] =  TCPOPT_NOP;
22773 				wptr[1] =  TCPOPT_WSCALE;
22774 				wptr[2] =  TCPOPT_WS_LEN;
22775 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22776 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22777 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22778 			}
22779 
22780 			if (tcp->tcp_snd_sack_ok) {
22781 				wptr = mp1->b_wptr;
22782 				wptr[0] = TCPOPT_NOP;
22783 				wptr[1] = TCPOPT_NOP;
22784 				wptr[2] = TCPOPT_SACK_PERMITTED;
22785 				wptr[3] = TCPOPT_SACK_OK_LEN;
22786 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22787 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22788 			}
22789 
22790 			/* allocb() of adequate mblk assures space */
22791 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22792 			    (uintptr_t)INT_MAX);
22793 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22794 			/*
22795 			 * Get IP set to checksum on our behalf
22796 			 * Include the adjustment for a source route if any.
22797 			 */
22798 			u1 += tcp->tcp_sum;
22799 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22800 			U16_TO_BE16(u1, tcph->th_sum);
22801 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22802 		}
22803 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22804 		    (seq + data_length) == tcp->tcp_fss) {
22805 			if (!tcp->tcp_fin_acked) {
22806 				flags |= TH_FIN;
22807 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22808 			}
22809 			if (!tcp->tcp_fin_sent) {
22810 				tcp->tcp_fin_sent = B_TRUE;
22811 				switch (tcp->tcp_state) {
22812 				case TCPS_SYN_RCVD:
22813 				case TCPS_ESTABLISHED:
22814 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22815 					break;
22816 				case TCPS_CLOSE_WAIT:
22817 					tcp->tcp_state = TCPS_LAST_ACK;
22818 					break;
22819 				}
22820 				if (tcp->tcp_suna == tcp->tcp_snxt)
22821 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22822 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22823 			}
22824 		}
22825 		/*
22826 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22827 		 * is smaller than seq, u1 will become a very huge value.
22828 		 * So the comparison will fail.  Also note that tcp_urp
22829 		 * should be positive, see RFC 793 page 17.
22830 		 */
22831 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22832 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22833 		    u1 < (uint32_t)(64 * 1024)) {
22834 			flags |= TH_URG;
22835 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
22836 			U32_TO_ABE16(u1, tcph->th_urp);
22837 		}
22838 	}
22839 	tcph->th_flags[0] = (uchar_t)flags;
22840 	tcp->tcp_rack = tcp->tcp_rnxt;
22841 	tcp->tcp_rack_cnt = 0;
22842 
22843 	if (tcp->tcp_snd_ts_ok) {
22844 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22845 			uint32_t llbolt = (uint32_t)lbolt;
22846 
22847 			U32_TO_BE32(llbolt,
22848 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22849 			U32_TO_BE32(tcp->tcp_ts_recent,
22850 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22851 		}
22852 	}
22853 
22854 	if (num_sack_blk > 0) {
22855 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22856 		sack_blk_t *tmp;
22857 		int32_t	i;
22858 
22859 		wptr[0] = TCPOPT_NOP;
22860 		wptr[1] = TCPOPT_NOP;
22861 		wptr[2] = TCPOPT_SACK;
22862 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22863 		    sizeof (sack_blk_t);
22864 		wptr += TCPOPT_REAL_SACK_LEN;
22865 
22866 		tmp = tcp->tcp_sack_list;
22867 		for (i = 0; i < num_sack_blk; i++) {
22868 			U32_TO_BE32(tmp[i].begin, wptr);
22869 			wptr += sizeof (tcp_seq);
22870 			U32_TO_BE32(tmp[i].end, wptr);
22871 			wptr += sizeof (tcp_seq);
22872 		}
22873 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22874 	}
22875 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22876 	data_length += (int)(mp1->b_wptr - rptr);
22877 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22878 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22879 	} else {
22880 		ip6_t *ip6 = (ip6_t *)(rptr +
22881 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22882 		    sizeof (ip6i_t) : 0));
22883 
22884 		ip6->ip6_plen = htons(data_length -
22885 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22886 	}
22887 
22888 	/*
22889 	 * Prime pump for IP
22890 	 * Include the adjustment for a source route if any.
22891 	 */
22892 	data_length -= tcp->tcp_ip_hdr_len;
22893 	data_length += tcp->tcp_sum;
22894 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22895 	U16_TO_ABE16(data_length, tcph->th_sum);
22896 	if (tcp->tcp_ip_forward_progress) {
22897 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22898 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22899 		tcp->tcp_ip_forward_progress = B_FALSE;
22900 	}
22901 	return (mp1);
22902 }
22903 
22904 /* This function handles the push timeout. */
22905 void
22906 tcp_push_timer(void *arg)
22907 {
22908 	conn_t	*connp = (conn_t *)arg;
22909 	tcp_t *tcp = connp->conn_tcp;
22910 
22911 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
22912 
22913 	ASSERT(tcp->tcp_listener == NULL);
22914 
22915 	ASSERT(!IPCL_IS_NONSTR(connp));
22916 
22917 	tcp->tcp_push_tid = 0;
22918 
22919 	if (tcp->tcp_rcv_list != NULL &&
22920 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
22921 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22922 }
22923 
22924 /*
22925  * This function handles delayed ACK timeout.
22926  */
22927 static void
22928 tcp_ack_timer(void *arg)
22929 {
22930 	conn_t	*connp = (conn_t *)arg;
22931 	tcp_t *tcp = connp->conn_tcp;
22932 	mblk_t *mp;
22933 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22934 
22935 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
22936 
22937 	tcp->tcp_ack_tid = 0;
22938 
22939 	if (tcp->tcp_fused)
22940 		return;
22941 
22942 	/*
22943 	 * Do not send ACK if there is no outstanding unack'ed data.
22944 	 */
22945 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22946 		return;
22947 	}
22948 
22949 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22950 		/*
22951 		 * Make sure we don't allow deferred ACKs to result in
22952 		 * timer-based ACKing.  If we have held off an ACK
22953 		 * when there was more than an mss here, and the timer
22954 		 * goes off, we have to worry about the possibility
22955 		 * that the sender isn't doing slow-start, or is out
22956 		 * of step with us for some other reason.  We fall
22957 		 * permanently back in the direction of
22958 		 * ACK-every-other-packet as suggested in RFC 1122.
22959 		 */
22960 		if (tcp->tcp_rack_abs_max > 2)
22961 			tcp->tcp_rack_abs_max--;
22962 		tcp->tcp_rack_cur_max = 2;
22963 	}
22964 	mp = tcp_ack_mp(tcp);
22965 
22966 	if (mp != NULL) {
22967 		BUMP_LOCAL(tcp->tcp_obsegs);
22968 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22969 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
22970 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22971 	}
22972 }
22973 
22974 
22975 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22976 static mblk_t *
22977 tcp_ack_mp(tcp_t *tcp)
22978 {
22979 	uint32_t	seq_no;
22980 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22981 
22982 	/*
22983 	 * There are a few cases to be considered while setting the sequence no.
22984 	 * Essentially, we can come here while processing an unacceptable pkt
22985 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
22986 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
22987 	 * If we are here for a zero window probe, stick with suna. In all
22988 	 * other cases, we check if suna + swnd encompasses snxt and set
22989 	 * the sequence number to snxt, if so. If snxt falls outside the
22990 	 * window (the receiver probably shrunk its window), we will go with
22991 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
22992 	 * receiver.
22993 	 */
22994 	if (tcp->tcp_zero_win_probe) {
22995 		seq_no = tcp->tcp_suna;
22996 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
22997 		ASSERT(tcp->tcp_swnd == 0);
22998 		seq_no = tcp->tcp_snxt;
22999 	} else {
23000 		seq_no = SEQ_GT(tcp->tcp_snxt,
23001 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23002 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23003 	}
23004 
23005 	if (tcp->tcp_valid_bits) {
23006 		/*
23007 		 * For the complex case where we have to send some
23008 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23009 		 */
23010 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23011 		    NULL, B_FALSE));
23012 	} else {
23013 		/* Generate a simple ACK */
23014 		int	data_length;
23015 		uchar_t	*rptr;
23016 		tcph_t	*tcph;
23017 		mblk_t	*mp1;
23018 		int32_t	tcp_hdr_len;
23019 		int32_t	tcp_tcp_hdr_len;
23020 		int32_t	num_sack_blk = 0;
23021 		int32_t sack_opt_len;
23022 
23023 		/*
23024 		 * Allocate space for TCP + IP headers
23025 		 * and link-level header
23026 		 */
23027 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23028 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23029 			    tcp->tcp_num_sack_blk);
23030 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23031 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23032 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23033 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23034 		} else {
23035 			tcp_hdr_len = tcp->tcp_hdr_len;
23036 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23037 		}
23038 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23039 		if (!mp1)
23040 			return (NULL);
23041 
23042 		/* Update the latest receive window size in TCP header. */
23043 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23044 		    tcp->tcp_tcph->th_win);
23045 		/* copy in prototype TCP + IP header */
23046 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23047 		mp1->b_rptr = rptr;
23048 		mp1->b_wptr = rptr + tcp_hdr_len;
23049 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23050 
23051 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23052 
23053 		/* Set the TCP sequence number. */
23054 		U32_TO_ABE32(seq_no, tcph->th_seq);
23055 
23056 		/* Set up the TCP flag field. */
23057 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23058 		if (tcp->tcp_ecn_echo_on)
23059 			tcph->th_flags[0] |= TH_ECE;
23060 
23061 		tcp->tcp_rack = tcp->tcp_rnxt;
23062 		tcp->tcp_rack_cnt = 0;
23063 
23064 		/* fill in timestamp option if in use */
23065 		if (tcp->tcp_snd_ts_ok) {
23066 			uint32_t llbolt = (uint32_t)lbolt;
23067 
23068 			U32_TO_BE32(llbolt,
23069 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23070 			U32_TO_BE32(tcp->tcp_ts_recent,
23071 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23072 		}
23073 
23074 		/* Fill in SACK options */
23075 		if (num_sack_blk > 0) {
23076 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23077 			sack_blk_t *tmp;
23078 			int32_t	i;
23079 
23080 			wptr[0] = TCPOPT_NOP;
23081 			wptr[1] = TCPOPT_NOP;
23082 			wptr[2] = TCPOPT_SACK;
23083 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23084 			    sizeof (sack_blk_t);
23085 			wptr += TCPOPT_REAL_SACK_LEN;
23086 
23087 			tmp = tcp->tcp_sack_list;
23088 			for (i = 0; i < num_sack_blk; i++) {
23089 				U32_TO_BE32(tmp[i].begin, wptr);
23090 				wptr += sizeof (tcp_seq);
23091 				U32_TO_BE32(tmp[i].end, wptr);
23092 				wptr += sizeof (tcp_seq);
23093 			}
23094 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23095 			    << 4);
23096 		}
23097 
23098 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23099 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23100 		} else {
23101 			/* Check for ip6i_t header in sticky hdrs */
23102 			ip6_t *ip6 = (ip6_t *)(rptr +
23103 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23104 			    sizeof (ip6i_t) : 0));
23105 
23106 			ip6->ip6_plen = htons(tcp_hdr_len -
23107 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23108 		}
23109 
23110 		/*
23111 		 * Prime pump for checksum calculation in IP.  Include the
23112 		 * adjustment for a source route if any.
23113 		 */
23114 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23115 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23116 		U16_TO_ABE16(data_length, tcph->th_sum);
23117 
23118 		if (tcp->tcp_ip_forward_progress) {
23119 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23120 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23121 			tcp->tcp_ip_forward_progress = B_FALSE;
23122 		}
23123 		return (mp1);
23124 	}
23125 }
23126 
23127 /*
23128  * Hash list insertion routine for tcp_t structures. Each hash bucket
23129  * contains a list of tcp_t entries, and each entry is bound to a unique
23130  * port. If there are multiple tcp_t's that are bound to the same port, then
23131  * one of them will be linked into the hash bucket list, and the rest will
23132  * hang off of that one entry. For each port, entries bound to a specific IP
23133  * address will be inserted before those those bound to INADDR_ANY.
23134  */
23135 static void
23136 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23137 {
23138 	tcp_t	**tcpp;
23139 	tcp_t	*tcpnext;
23140 	tcp_t	*tcphash;
23141 
23142 	if (tcp->tcp_ptpbhn != NULL) {
23143 		ASSERT(!caller_holds_lock);
23144 		tcp_bind_hash_remove(tcp);
23145 	}
23146 	tcpp = &tbf->tf_tcp;
23147 	if (!caller_holds_lock) {
23148 		mutex_enter(&tbf->tf_lock);
23149 	} else {
23150 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23151 	}
23152 	tcphash = tcpp[0];
23153 	tcpnext = NULL;
23154 	if (tcphash != NULL) {
23155 		/* Look for an entry using the same port */
23156 		while ((tcphash = tcpp[0]) != NULL &&
23157 		    tcp->tcp_lport != tcphash->tcp_lport)
23158 			tcpp = &(tcphash->tcp_bind_hash);
23159 
23160 		/* The port was not found, just add to the end */
23161 		if (tcphash == NULL)
23162 			goto insert;
23163 
23164 		/*
23165 		 * OK, there already exists an entry bound to the
23166 		 * same port.
23167 		 *
23168 		 * If the new tcp bound to the INADDR_ANY address
23169 		 * and the first one in the list is not bound to
23170 		 * INADDR_ANY we skip all entries until we find the
23171 		 * first one bound to INADDR_ANY.
23172 		 * This makes sure that applications binding to a
23173 		 * specific address get preference over those binding to
23174 		 * INADDR_ANY.
23175 		 */
23176 		tcpnext = tcphash;
23177 		tcphash = NULL;
23178 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23179 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23180 			while ((tcpnext = tcpp[0]) != NULL &&
23181 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23182 				tcpp = &(tcpnext->tcp_bind_hash_port);
23183 
23184 			if (tcpnext) {
23185 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23186 				tcphash = tcpnext->tcp_bind_hash;
23187 				if (tcphash != NULL) {
23188 					tcphash->tcp_ptpbhn =
23189 					    &(tcp->tcp_bind_hash);
23190 					tcpnext->tcp_bind_hash = NULL;
23191 				}
23192 			}
23193 		} else {
23194 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23195 			tcphash = tcpnext->tcp_bind_hash;
23196 			if (tcphash != NULL) {
23197 				tcphash->tcp_ptpbhn =
23198 				    &(tcp->tcp_bind_hash);
23199 				tcpnext->tcp_bind_hash = NULL;
23200 			}
23201 		}
23202 	}
23203 insert:
23204 	tcp->tcp_bind_hash_port = tcpnext;
23205 	tcp->tcp_bind_hash = tcphash;
23206 	tcp->tcp_ptpbhn = tcpp;
23207 	tcpp[0] = tcp;
23208 	if (!caller_holds_lock)
23209 		mutex_exit(&tbf->tf_lock);
23210 }
23211 
23212 /*
23213  * Hash list removal routine for tcp_t structures.
23214  */
23215 static void
23216 tcp_bind_hash_remove(tcp_t *tcp)
23217 {
23218 	tcp_t	*tcpnext;
23219 	kmutex_t *lockp;
23220 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23221 
23222 	if (tcp->tcp_ptpbhn == NULL)
23223 		return;
23224 
23225 	/*
23226 	 * Extract the lock pointer in case there are concurrent
23227 	 * hash_remove's for this instance.
23228 	 */
23229 	ASSERT(tcp->tcp_lport != 0);
23230 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23231 
23232 	ASSERT(lockp != NULL);
23233 	mutex_enter(lockp);
23234 	if (tcp->tcp_ptpbhn) {
23235 		tcpnext = tcp->tcp_bind_hash_port;
23236 		if (tcpnext != NULL) {
23237 			tcp->tcp_bind_hash_port = NULL;
23238 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23239 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23240 			if (tcpnext->tcp_bind_hash != NULL) {
23241 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23242 				    &(tcpnext->tcp_bind_hash);
23243 				tcp->tcp_bind_hash = NULL;
23244 			}
23245 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23246 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23247 			tcp->tcp_bind_hash = NULL;
23248 		}
23249 		*tcp->tcp_ptpbhn = tcpnext;
23250 		tcp->tcp_ptpbhn = NULL;
23251 	}
23252 	mutex_exit(lockp);
23253 }
23254 
23255 
23256 /*
23257  * Hash list lookup routine for tcp_t structures.
23258  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23259  */
23260 static tcp_t *
23261 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23262 {
23263 	tf_t	*tf;
23264 	tcp_t	*tcp;
23265 
23266 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23267 	mutex_enter(&tf->tf_lock);
23268 	for (tcp = tf->tf_tcp; tcp != NULL;
23269 	    tcp = tcp->tcp_acceptor_hash) {
23270 		if (tcp->tcp_acceptor_id == id) {
23271 			CONN_INC_REF(tcp->tcp_connp);
23272 			mutex_exit(&tf->tf_lock);
23273 			return (tcp);
23274 		}
23275 	}
23276 	mutex_exit(&tf->tf_lock);
23277 	return (NULL);
23278 }
23279 
23280 
23281 /*
23282  * Hash list insertion routine for tcp_t structures.
23283  */
23284 void
23285 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23286 {
23287 	tf_t	*tf;
23288 	tcp_t	**tcpp;
23289 	tcp_t	*tcpnext;
23290 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23291 
23292 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23293 
23294 	if (tcp->tcp_ptpahn != NULL)
23295 		tcp_acceptor_hash_remove(tcp);
23296 	tcpp = &tf->tf_tcp;
23297 	mutex_enter(&tf->tf_lock);
23298 	tcpnext = tcpp[0];
23299 	if (tcpnext)
23300 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23301 	tcp->tcp_acceptor_hash = tcpnext;
23302 	tcp->tcp_ptpahn = tcpp;
23303 	tcpp[0] = tcp;
23304 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23305 	mutex_exit(&tf->tf_lock);
23306 }
23307 
23308 /*
23309  * Hash list removal routine for tcp_t structures.
23310  */
23311 static void
23312 tcp_acceptor_hash_remove(tcp_t *tcp)
23313 {
23314 	tcp_t	*tcpnext;
23315 	kmutex_t *lockp;
23316 
23317 	/*
23318 	 * Extract the lock pointer in case there are concurrent
23319 	 * hash_remove's for this instance.
23320 	 */
23321 	lockp = tcp->tcp_acceptor_lockp;
23322 
23323 	if (tcp->tcp_ptpahn == NULL)
23324 		return;
23325 
23326 	ASSERT(lockp != NULL);
23327 	mutex_enter(lockp);
23328 	if (tcp->tcp_ptpahn) {
23329 		tcpnext = tcp->tcp_acceptor_hash;
23330 		if (tcpnext) {
23331 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23332 			tcp->tcp_acceptor_hash = NULL;
23333 		}
23334 		*tcp->tcp_ptpahn = tcpnext;
23335 		tcp->tcp_ptpahn = NULL;
23336 	}
23337 	mutex_exit(lockp);
23338 	tcp->tcp_acceptor_lockp = NULL;
23339 }
23340 
23341 /*
23342  * Type three generator adapted from the random() function in 4.4 BSD:
23343  */
23344 
23345 /*
23346  * Copyright (c) 1983, 1993
23347  *	The Regents of the University of California.  All rights reserved.
23348  *
23349  * Redistribution and use in source and binary forms, with or without
23350  * modification, are permitted provided that the following conditions
23351  * are met:
23352  * 1. Redistributions of source code must retain the above copyright
23353  *    notice, this list of conditions and the following disclaimer.
23354  * 2. Redistributions in binary form must reproduce the above copyright
23355  *    notice, this list of conditions and the following disclaimer in the
23356  *    documentation and/or other materials provided with the distribution.
23357  * 3. All advertising materials mentioning features or use of this software
23358  *    must display the following acknowledgement:
23359  *	This product includes software developed by the University of
23360  *	California, Berkeley and its contributors.
23361  * 4. Neither the name of the University nor the names of its contributors
23362  *    may be used to endorse or promote products derived from this software
23363  *    without specific prior written permission.
23364  *
23365  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23366  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23367  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23368  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23369  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23370  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23371  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23372  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23373  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23374  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23375  * SUCH DAMAGE.
23376  */
23377 
23378 /* Type 3 -- x**31 + x**3 + 1 */
23379 #define	DEG_3		31
23380 #define	SEP_3		3
23381 
23382 
23383 /* Protected by tcp_random_lock */
23384 static int tcp_randtbl[DEG_3 + 1];
23385 
23386 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23387 static int *tcp_random_rptr = &tcp_randtbl[1];
23388 
23389 static int *tcp_random_state = &tcp_randtbl[1];
23390 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23391 
23392 kmutex_t tcp_random_lock;
23393 
23394 void
23395 tcp_random_init(void)
23396 {
23397 	int i;
23398 	hrtime_t hrt;
23399 	time_t wallclock;
23400 	uint64_t result;
23401 
23402 	/*
23403 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23404 	 * a longlong, which may contain resolution down to nanoseconds.
23405 	 * The current time will either be a 32-bit or a 64-bit quantity.
23406 	 * XOR the two together in a 64-bit result variable.
23407 	 * Convert the result to a 32-bit value by multiplying the high-order
23408 	 * 32-bits by the low-order 32-bits.
23409 	 */
23410 
23411 	hrt = gethrtime();
23412 	(void) drv_getparm(TIME, &wallclock);
23413 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23414 	mutex_enter(&tcp_random_lock);
23415 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23416 	    (result & 0xffffffff);
23417 
23418 	for (i = 1; i < DEG_3; i++)
23419 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23420 		    + 12345;
23421 	tcp_random_fptr = &tcp_random_state[SEP_3];
23422 	tcp_random_rptr = &tcp_random_state[0];
23423 	mutex_exit(&tcp_random_lock);
23424 	for (i = 0; i < 10 * DEG_3; i++)
23425 		(void) tcp_random();
23426 }
23427 
23428 /*
23429  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23430  * This range is selected to be approximately centered on TCP_ISS / 2,
23431  * and easy to compute. We get this value by generating a 32-bit random
23432  * number, selecting out the high-order 17 bits, and then adding one so
23433  * that we never return zero.
23434  */
23435 int
23436 tcp_random(void)
23437 {
23438 	int i;
23439 
23440 	mutex_enter(&tcp_random_lock);
23441 	*tcp_random_fptr += *tcp_random_rptr;
23442 
23443 	/*
23444 	 * The high-order bits are more random than the low-order bits,
23445 	 * so we select out the high-order 17 bits and add one so that
23446 	 * we never return zero.
23447 	 */
23448 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23449 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23450 		tcp_random_fptr = tcp_random_state;
23451 		++tcp_random_rptr;
23452 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23453 		tcp_random_rptr = tcp_random_state;
23454 
23455 	mutex_exit(&tcp_random_lock);
23456 	return (i);
23457 }
23458 
23459 static int
23460 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23461     int *t_errorp, int *sys_errorp)
23462 {
23463 	int error;
23464 	int is_absreq_failure;
23465 	t_scalar_t *opt_lenp;
23466 	t_scalar_t opt_offset;
23467 	int prim_type;
23468 	struct T_conn_req *tcreqp;
23469 	struct T_conn_res *tcresp;
23470 	cred_t *cr;
23471 
23472 	/*
23473 	 * All Solaris components should pass a db_credp
23474 	 * for this TPI message, hence we ASSERT.
23475 	 * But in case there is some other M_PROTO that looks
23476 	 * like a TPI message sent by some other kernel
23477 	 * component, we check and return an error.
23478 	 */
23479 	cr = msg_getcred(mp, NULL);
23480 	ASSERT(cr != NULL);
23481 	if (cr == NULL)
23482 		return (-1);
23483 
23484 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23485 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23486 	    prim_type == T_CONN_RES);
23487 
23488 	switch (prim_type) {
23489 	case T_CONN_REQ:
23490 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23491 		opt_offset = tcreqp->OPT_offset;
23492 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23493 		break;
23494 	case O_T_CONN_RES:
23495 	case T_CONN_RES:
23496 		tcresp = (struct T_conn_res *)mp->b_rptr;
23497 		opt_offset = tcresp->OPT_offset;
23498 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23499 		break;
23500 	}
23501 
23502 	*t_errorp = 0;
23503 	*sys_errorp = 0;
23504 	*do_disconnectp = 0;
23505 
23506 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23507 	    opt_offset, cr, &tcp_opt_obj,
23508 	    NULL, &is_absreq_failure);
23509 
23510 	switch (error) {
23511 	case  0:		/* no error */
23512 		ASSERT(is_absreq_failure == 0);
23513 		return (0);
23514 	case ENOPROTOOPT:
23515 		*t_errorp = TBADOPT;
23516 		break;
23517 	case EACCES:
23518 		*t_errorp = TACCES;
23519 		break;
23520 	default:
23521 		*t_errorp = TSYSERR; *sys_errorp = error;
23522 		break;
23523 	}
23524 	if (is_absreq_failure != 0) {
23525 		/*
23526 		 * The connection request should get the local ack
23527 		 * T_OK_ACK and then a T_DISCON_IND.
23528 		 */
23529 		*do_disconnectp = 1;
23530 	}
23531 	return (-1);
23532 }
23533 
23534 /*
23535  * Split this function out so that if the secret changes, I'm okay.
23536  *
23537  * Initialize the tcp_iss_cookie and tcp_iss_key.
23538  */
23539 
23540 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23541 
23542 static void
23543 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
23544 {
23545 	struct {
23546 		int32_t current_time;
23547 		uint32_t randnum;
23548 		uint16_t pad;
23549 		uint8_t ether[6];
23550 		uint8_t passwd[PASSWD_SIZE];
23551 	} tcp_iss_cookie;
23552 	time_t t;
23553 
23554 	/*
23555 	 * Start with the current absolute time.
23556 	 */
23557 	(void) drv_getparm(TIME, &t);
23558 	tcp_iss_cookie.current_time = t;
23559 
23560 	/*
23561 	 * XXX - Need a more random number per RFC 1750, not this crap.
23562 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23563 	 */
23564 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23565 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23566 
23567 	/*
23568 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23569 	 * as a good template.
23570 	 */
23571 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23572 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23573 
23574 	/*
23575 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23576 	 */
23577 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23578 
23579 	/*
23580 	 * See 4010593 if this section becomes a problem again,
23581 	 * but the local ethernet address is useful here.
23582 	 */
23583 	(void) localetheraddr(NULL,
23584 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23585 
23586 	/*
23587 	 * Hash 'em all together.  The MD5Final is called per-connection.
23588 	 */
23589 	mutex_enter(&tcps->tcps_iss_key_lock);
23590 	MD5Init(&tcps->tcps_iss_key);
23591 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
23592 	    sizeof (tcp_iss_cookie));
23593 	mutex_exit(&tcps->tcps_iss_key_lock);
23594 }
23595 
23596 /*
23597  * Set the RFC 1948 pass phrase
23598  */
23599 /* ARGSUSED */
23600 static int
23601 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23602     cred_t *cr)
23603 {
23604 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23605 
23606 	/*
23607 	 * Basically, value contains a new pass phrase.  Pass it along!
23608 	 */
23609 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
23610 	return (0);
23611 }
23612 
23613 /* ARGSUSED */
23614 static int
23615 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23616 {
23617 	bzero(buf, sizeof (tcp_sack_info_t));
23618 	return (0);
23619 }
23620 
23621 /* ARGSUSED */
23622 static int
23623 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23624 {
23625 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23626 	return (0);
23627 }
23628 
23629 /*
23630  * Make sure we wait until the default queue is setup, yet allow
23631  * tcp_g_q_create() to open a TCP stream.
23632  * We need to allow tcp_g_q_create() do do an open
23633  * of tcp, hence we compare curhread.
23634  * All others have to wait until the tcps_g_q has been
23635  * setup.
23636  */
23637 void
23638 tcp_g_q_setup(tcp_stack_t *tcps)
23639 {
23640 	mutex_enter(&tcps->tcps_g_q_lock);
23641 	if (tcps->tcps_g_q != NULL) {
23642 		mutex_exit(&tcps->tcps_g_q_lock);
23643 		return;
23644 	}
23645 	if (tcps->tcps_g_q_creator == NULL) {
23646 		/* This thread will set it up */
23647 		tcps->tcps_g_q_creator = curthread;
23648 		mutex_exit(&tcps->tcps_g_q_lock);
23649 		tcp_g_q_create(tcps);
23650 		mutex_enter(&tcps->tcps_g_q_lock);
23651 		ASSERT(tcps->tcps_g_q_creator == curthread);
23652 		tcps->tcps_g_q_creator = NULL;
23653 		cv_signal(&tcps->tcps_g_q_cv);
23654 		ASSERT(tcps->tcps_g_q != NULL);
23655 		mutex_exit(&tcps->tcps_g_q_lock);
23656 		return;
23657 	}
23658 	/* Everybody but the creator has to wait */
23659 	if (tcps->tcps_g_q_creator != curthread) {
23660 		while (tcps->tcps_g_q == NULL)
23661 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
23662 	}
23663 	mutex_exit(&tcps->tcps_g_q_lock);
23664 }
23665 
23666 #define	IP	"ip"
23667 
23668 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
23669 
23670 /*
23671  * Create a default tcp queue here instead of in strplumb
23672  */
23673 void
23674 tcp_g_q_create(tcp_stack_t *tcps)
23675 {
23676 	int error;
23677 	ldi_handle_t	lh = NULL;
23678 	ldi_ident_t	li = NULL;
23679 	int		rval;
23680 	cred_t		*cr;
23681 	major_t IP_MAJ;
23682 
23683 #ifdef NS_DEBUG
23684 	(void) printf("tcp_g_q_create()\n");
23685 #endif
23686 
23687 	IP_MAJ = ddi_name_to_major(IP);
23688 
23689 	ASSERT(tcps->tcps_g_q_creator == curthread);
23690 
23691 	error = ldi_ident_from_major(IP_MAJ, &li);
23692 	if (error) {
23693 #ifdef DEBUG
23694 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
23695 		    error);
23696 #endif
23697 		return;
23698 	}
23699 
23700 	cr = zone_get_kcred(netstackid_to_zoneid(
23701 	    tcps->tcps_netstack->netstack_stackid));
23702 	ASSERT(cr != NULL);
23703 	/*
23704 	 * We set the tcp default queue to IPv6 because IPv4 falls
23705 	 * back to IPv6 when it can't find a client, but
23706 	 * IPv6 does not fall back to IPv4.
23707 	 */
23708 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
23709 	if (error) {
23710 #ifdef DEBUG
23711 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
23712 		    error);
23713 #endif
23714 		goto out;
23715 	}
23716 
23717 	/*
23718 	 * This ioctl causes the tcp framework to cache a pointer to
23719 	 * this stream, so we don't want to close the stream after
23720 	 * this operation.
23721 	 * Use the kernel credentials that are for the zone we're in.
23722 	 */
23723 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
23724 	    (intptr_t)0, FKIOCTL, cr, &rval);
23725 	if (error) {
23726 #ifdef DEBUG
23727 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
23728 		    "error %d\n", error);
23729 #endif
23730 		goto out;
23731 	}
23732 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
23733 	lh = NULL;
23734 out:
23735 	/* Close layered handles */
23736 	if (li)
23737 		ldi_ident_release(li);
23738 	/* Keep cred around until _inactive needs it */
23739 	tcps->tcps_g_q_cr = cr;
23740 }
23741 
23742 /*
23743  * We keep tcp_g_q set until all other tcp_t's in the zone
23744  * has gone away, and then when tcp_g_q_inactive() is called
23745  * we clear it.
23746  */
23747 void
23748 tcp_g_q_destroy(tcp_stack_t *tcps)
23749 {
23750 #ifdef NS_DEBUG
23751 	(void) printf("tcp_g_q_destroy()for stack %d\n",
23752 	    tcps->tcps_netstack->netstack_stackid);
23753 #endif
23754 
23755 	if (tcps->tcps_g_q == NULL) {
23756 		return;	/* Nothing to cleanup */
23757 	}
23758 	/*
23759 	 * Drop reference corresponding to the default queue.
23760 	 * This reference was added from tcp_open when the default queue
23761 	 * was created, hence we compensate for this extra drop in
23762 	 * tcp_g_q_close. If the refcnt drops to zero here it means
23763 	 * the default queue was the last one to be open, in which
23764 	 * case, then tcp_g_q_inactive will be
23765 	 * called as a result of the refrele.
23766 	 */
23767 	TCPS_REFRELE(tcps);
23768 }
23769 
23770 /*
23771  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23772  * Run by tcp_q_q_inactive using a taskq.
23773  */
23774 static void
23775 tcp_g_q_close(void *arg)
23776 {
23777 	tcp_stack_t *tcps = arg;
23778 	int error;
23779 	ldi_handle_t	lh = NULL;
23780 	ldi_ident_t	li = NULL;
23781 	cred_t		*cr;
23782 	major_t IP_MAJ;
23783 
23784 	IP_MAJ = ddi_name_to_major(IP);
23785 
23786 #ifdef NS_DEBUG
23787 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
23788 	    tcps->tcps_netstack->netstack_stackid,
23789 	    tcps->tcps_netstack->netstack_refcnt);
23790 #endif
23791 	lh = tcps->tcps_g_q_lh;
23792 	if (lh == NULL)
23793 		return;	/* Nothing to cleanup */
23794 
23795 	ASSERT(tcps->tcps_refcnt == 1);
23796 	ASSERT(tcps->tcps_g_q != NULL);
23797 
23798 	error = ldi_ident_from_major(IP_MAJ, &li);
23799 	if (error) {
23800 #ifdef DEBUG
23801 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
23802 		    error);
23803 #endif
23804 		return;
23805 	}
23806 
23807 	cr = tcps->tcps_g_q_cr;
23808 	tcps->tcps_g_q_cr = NULL;
23809 	ASSERT(cr != NULL);
23810 
23811 	/*
23812 	 * Make sure we can break the recursion when tcp_close decrements
23813 	 * the reference count causing g_q_inactive to be called again.
23814 	 */
23815 	tcps->tcps_g_q_lh = NULL;
23816 
23817 	/* close the default queue */
23818 	(void) ldi_close(lh, FREAD|FWRITE, cr);
23819 	/*
23820 	 * At this point in time tcps and the rest of netstack_t might
23821 	 * have been deleted.
23822 	 */
23823 	tcps = NULL;
23824 
23825 	/* Close layered handles */
23826 	ldi_ident_release(li);
23827 	crfree(cr);
23828 }
23829 
23830 /*
23831  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23832  *
23833  * Have to ensure that the ldi routines are not used by an
23834  * interrupt thread by using a taskq.
23835  */
23836 void
23837 tcp_g_q_inactive(tcp_stack_t *tcps)
23838 {
23839 	if (tcps->tcps_g_q_lh == NULL)
23840 		return;	/* Nothing to cleanup */
23841 
23842 	ASSERT(tcps->tcps_refcnt == 0);
23843 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
23844 
23845 	if (servicing_interrupt()) {
23846 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
23847 		    (void *) tcps, TQ_SLEEP);
23848 	} else {
23849 		tcp_g_q_close(tcps);
23850 	}
23851 }
23852 
23853 /*
23854  * Called by IP when IP is loaded into the kernel
23855  */
23856 void
23857 tcp_ddi_g_init(void)
23858 {
23859 	tcp_timercache = kmem_cache_create("tcp_timercache",
23860 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23861 	    NULL, NULL, NULL, NULL, NULL, 0);
23862 
23863 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23864 	    sizeof (tcp_sack_info_t), 0,
23865 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23866 
23867 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23868 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23869 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23870 
23871 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23872 
23873 	/* Initialize the random number generator */
23874 	tcp_random_init();
23875 
23876 	/* A single callback independently of how many netstacks we have */
23877 	ip_squeue_init(tcp_squeue_add);
23878 
23879 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
23880 
23881 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
23882 	    TASKQ_PREPOPULATE);
23883 
23884 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
23885 
23886 	/*
23887 	 * We want to be informed each time a stack is created or
23888 	 * destroyed in the kernel, so we can maintain the
23889 	 * set of tcp_stack_t's.
23890 	 */
23891 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
23892 	    tcp_stack_fini);
23893 }
23894 
23895 
23896 #define	INET_NAME	"ip"
23897 
23898 /*
23899  * Initialize the TCP stack instance.
23900  */
23901 static void *
23902 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
23903 {
23904 	tcp_stack_t	*tcps;
23905 	tcpparam_t	*pa;
23906 	int		i;
23907 	int		error = 0;
23908 	major_t		major;
23909 
23910 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
23911 	tcps->tcps_netstack = ns;
23912 
23913 	/* Initialize locks */
23914 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23915 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
23916 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23917 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23918 
23919 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
23920 	tcps->tcps_g_epriv_ports[0] = 2049;
23921 	tcps->tcps_g_epriv_ports[1] = 4045;
23922 	tcps->tcps_min_anonpriv_port = 512;
23923 
23924 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
23925 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
23926 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
23927 	    TCP_FANOUT_SIZE, KM_SLEEP);
23928 
23929 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
23930 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
23931 		    MUTEX_DEFAULT, NULL);
23932 	}
23933 
23934 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
23935 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
23936 		    MUTEX_DEFAULT, NULL);
23937 	}
23938 
23939 	/* TCP's IPsec code calls the packet dropper. */
23940 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
23941 
23942 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
23943 	tcps->tcps_params = pa;
23944 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
23945 
23946 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
23947 	    A_CNT(lcl_tcp_param_arr), tcps);
23948 
23949 	/*
23950 	 * Note: To really walk the device tree you need the devinfo
23951 	 * pointer to your device which is only available after probe/attach.
23952 	 * The following is safe only because it uses ddi_root_node()
23953 	 */
23954 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23955 	    tcp_opt_obj.odb_opt_arr_cnt);
23956 
23957 	/*
23958 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23959 	 * by the boot scripts.
23960 	 *
23961 	 * Use NULL name, as the name is caught by the new lockstats.
23962 	 *
23963 	 * Initialize with some random, non-guessable string, like the global
23964 	 * T_INFO_ACK.
23965 	 */
23966 
23967 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23968 	    sizeof (tcp_g_t_info_ack), tcps);
23969 
23970 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
23971 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
23972 
23973 	major = mod_name_to_major(INET_NAME);
23974 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
23975 	ASSERT(error == 0);
23976 	return (tcps);
23977 }
23978 
23979 /*
23980  * Called when the IP module is about to be unloaded.
23981  */
23982 void
23983 tcp_ddi_g_destroy(void)
23984 {
23985 	tcp_g_kstat_fini(tcp_g_kstat);
23986 	tcp_g_kstat = NULL;
23987 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
23988 
23989 	mutex_destroy(&tcp_random_lock);
23990 
23991 	kmem_cache_destroy(tcp_timercache);
23992 	kmem_cache_destroy(tcp_sack_info_cache);
23993 	kmem_cache_destroy(tcp_iphc_cache);
23994 
23995 	netstack_unregister(NS_TCP);
23996 	taskq_destroy(tcp_taskq);
23997 }
23998 
23999 /*
24000  * Shut down the TCP stack instance.
24001  */
24002 /* ARGSUSED */
24003 static void
24004 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24005 {
24006 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24007 
24008 	tcp_g_q_destroy(tcps);
24009 }
24010 
24011 /*
24012  * Free the TCP stack instance.
24013  */
24014 static void
24015 tcp_stack_fini(netstackid_t stackid, void *arg)
24016 {
24017 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24018 	int i;
24019 
24020 	nd_free(&tcps->tcps_g_nd);
24021 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24022 	tcps->tcps_params = NULL;
24023 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24024 	tcps->tcps_wroff_xtra_param = NULL;
24025 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24026 	tcps->tcps_mdt_head_param = NULL;
24027 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24028 	tcps->tcps_mdt_tail_param = NULL;
24029 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24030 	tcps->tcps_mdt_max_pbufs_param = NULL;
24031 
24032 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24033 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24034 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24035 	}
24036 
24037 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24038 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24039 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24040 	}
24041 
24042 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24043 	tcps->tcps_bind_fanout = NULL;
24044 
24045 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24046 	tcps->tcps_acceptor_fanout = NULL;
24047 
24048 	mutex_destroy(&tcps->tcps_iss_key_lock);
24049 	mutex_destroy(&tcps->tcps_g_q_lock);
24050 	cv_destroy(&tcps->tcps_g_q_cv);
24051 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24052 
24053 	ip_drop_unregister(&tcps->tcps_dropper);
24054 
24055 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24056 	tcps->tcps_kstat = NULL;
24057 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24058 
24059 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24060 	tcps->tcps_mibkp = NULL;
24061 
24062 	ldi_ident_release(tcps->tcps_ldi_ident);
24063 	kmem_free(tcps, sizeof (*tcps));
24064 }
24065 
24066 /*
24067  * Generate ISS, taking into account NDD changes may happen halfway through.
24068  * (If the iss is not zero, set it.)
24069  */
24070 
24071 static void
24072 tcp_iss_init(tcp_t *tcp)
24073 {
24074 	MD5_CTX context;
24075 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24076 	uint32_t answer[4];
24077 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24078 
24079 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24080 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24081 	switch (tcps->tcps_strong_iss) {
24082 	case 2:
24083 		mutex_enter(&tcps->tcps_iss_key_lock);
24084 		context = tcps->tcps_iss_key;
24085 		mutex_exit(&tcps->tcps_iss_key_lock);
24086 		arg.ports = tcp->tcp_ports;
24087 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24088 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24089 			    &arg.src);
24090 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24091 			    &arg.dst);
24092 		} else {
24093 			arg.src = tcp->tcp_ip6h->ip6_src;
24094 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24095 		}
24096 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24097 		MD5Final((uchar_t *)answer, &context);
24098 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24099 		/*
24100 		 * Now that we've hashed into a unique per-connection sequence
24101 		 * space, add a random increment per strong_iss == 1.  So I
24102 		 * guess we'll have to...
24103 		 */
24104 		/* FALLTHRU */
24105 	case 1:
24106 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24107 		break;
24108 	default:
24109 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24110 		break;
24111 	}
24112 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24113 	tcp->tcp_fss = tcp->tcp_iss - 1;
24114 	tcp->tcp_suna = tcp->tcp_iss;
24115 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24116 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24117 	tcp->tcp_csuna = tcp->tcp_snxt;
24118 }
24119 
24120 /*
24121  * Exported routine for extracting active tcp connection status.
24122  *
24123  * This is used by the Solaris Cluster Networking software to
24124  * gather a list of connections that need to be forwarded to
24125  * specific nodes in the cluster when configuration changes occur.
24126  *
24127  * The callback is invoked for each tcp_t structure from all netstacks,
24128  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24129  * from the netstack with the specified stack_id. Returning
24130  * non-zero from the callback routine terminates the search.
24131  */
24132 int
24133 cl_tcp_walk_list(netstackid_t stack_id,
24134     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24135 {
24136 	netstack_handle_t nh;
24137 	netstack_t *ns;
24138 	int ret = 0;
24139 
24140 	if (stack_id >= 0) {
24141 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24142 			return (EINVAL);
24143 
24144 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24145 		    ns->netstack_tcp);
24146 		netstack_rele(ns);
24147 		return (ret);
24148 	}
24149 
24150 	netstack_next_init(&nh);
24151 	while ((ns = netstack_next(&nh)) != NULL) {
24152 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24153 		    ns->netstack_tcp);
24154 		netstack_rele(ns);
24155 	}
24156 	netstack_next_fini(&nh);
24157 	return (ret);
24158 }
24159 
24160 static int
24161 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
24162     tcp_stack_t *tcps)
24163 {
24164 	tcp_t *tcp;
24165 	cl_tcp_info_t	cl_tcpi;
24166 	connf_t	*connfp;
24167 	conn_t	*connp;
24168 	int	i;
24169 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24170 
24171 	ASSERT(callback != NULL);
24172 
24173 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24174 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
24175 		connp = NULL;
24176 
24177 		while ((connp =
24178 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24179 
24180 			tcp = connp->conn_tcp;
24181 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24182 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24183 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24184 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24185 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24186 			/*
24187 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24188 			 * addresses. They are copied implicitly below as
24189 			 * mapped addresses.
24190 			 */
24191 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24192 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24193 				cl_tcpi.cl_tcpi_faddr =
24194 				    tcp->tcp_ipha->ipha_dst;
24195 			} else {
24196 				cl_tcpi.cl_tcpi_faddr_v6 =
24197 				    tcp->tcp_ip6h->ip6_dst;
24198 			}
24199 
24200 			/*
24201 			 * If the callback returns non-zero
24202 			 * we terminate the traversal.
24203 			 */
24204 			if ((*callback)(&cl_tcpi, arg) != 0) {
24205 				CONN_DEC_REF(tcp->tcp_connp);
24206 				return (1);
24207 			}
24208 		}
24209 	}
24210 
24211 	return (0);
24212 }
24213 
24214 /*
24215  * Macros used for accessing the different types of sockaddr
24216  * structures inside a tcp_ioc_abort_conn_t.
24217  */
24218 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24219 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24220 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24221 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24222 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24223 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24224 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24225 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24226 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24227 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24228 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24229 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24230 
24231 /*
24232  * Return the correct error code to mimic the behavior
24233  * of a connection reset.
24234  */
24235 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24236 		switch ((state)) {		\
24237 		case TCPS_SYN_SENT:		\
24238 		case TCPS_SYN_RCVD:		\
24239 			(err) = ECONNREFUSED;	\
24240 			break;			\
24241 		case TCPS_ESTABLISHED:		\
24242 		case TCPS_FIN_WAIT_1:		\
24243 		case TCPS_FIN_WAIT_2:		\
24244 		case TCPS_CLOSE_WAIT:		\
24245 			(err) = ECONNRESET;	\
24246 			break;			\
24247 		case TCPS_CLOSING:		\
24248 		case TCPS_LAST_ACK:		\
24249 		case TCPS_TIME_WAIT:		\
24250 			(err) = 0;		\
24251 			break;			\
24252 		default:			\
24253 			(err) = ENXIO;		\
24254 		}				\
24255 	}
24256 
24257 /*
24258  * Check if a tcp structure matches the info in acp.
24259  */
24260 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24261 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24262 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24263 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24264 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24265 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24266 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24267 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24268 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24269 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24270 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24271 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24272 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24273 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24274 	&(tcp)->tcp_ip_src_v6)) &&				\
24275 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24276 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24277 	&(tcp)->tcp_remote_v6)) &&				\
24278 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24279 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24280 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24281 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24282 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24283 	(acp)->ac_end >= (tcp)->tcp_state))
24284 
24285 #define	TCP_AC_MATCH(acp, tcp)					\
24286 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24287 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24288 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24289 
24290 /*
24291  * Build a message containing a tcp_ioc_abort_conn_t structure
24292  * which is filled in with information from acp and tp.
24293  */
24294 static mblk_t *
24295 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24296 {
24297 	mblk_t *mp;
24298 	tcp_ioc_abort_conn_t *tacp;
24299 
24300 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24301 	if (mp == NULL)
24302 		return (NULL);
24303 
24304 	mp->b_datap->db_type = M_CTL;
24305 
24306 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24307 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24308 	    sizeof (uint32_t));
24309 
24310 	tacp->ac_start = acp->ac_start;
24311 	tacp->ac_end = acp->ac_end;
24312 	tacp->ac_zoneid = acp->ac_zoneid;
24313 
24314 	if (acp->ac_local.ss_family == AF_INET) {
24315 		tacp->ac_local.ss_family = AF_INET;
24316 		tacp->ac_remote.ss_family = AF_INET;
24317 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24318 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24319 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24320 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24321 	} else {
24322 		tacp->ac_local.ss_family = AF_INET6;
24323 		tacp->ac_remote.ss_family = AF_INET6;
24324 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24325 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24326 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24327 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24328 	}
24329 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24330 	return (mp);
24331 }
24332 
24333 /*
24334  * Print a tcp_ioc_abort_conn_t structure.
24335  */
24336 static void
24337 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24338 {
24339 	char lbuf[128];
24340 	char rbuf[128];
24341 	sa_family_t af;
24342 	in_port_t lport, rport;
24343 	ushort_t logflags;
24344 
24345 	af = acp->ac_local.ss_family;
24346 
24347 	if (af == AF_INET) {
24348 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24349 		    lbuf, 128);
24350 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24351 		    rbuf, 128);
24352 		lport = ntohs(TCP_AC_V4LPORT(acp));
24353 		rport = ntohs(TCP_AC_V4RPORT(acp));
24354 	} else {
24355 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24356 		    lbuf, 128);
24357 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24358 		    rbuf, 128);
24359 		lport = ntohs(TCP_AC_V6LPORT(acp));
24360 		rport = ntohs(TCP_AC_V6RPORT(acp));
24361 	}
24362 
24363 	logflags = SL_TRACE | SL_NOTE;
24364 	/*
24365 	 * Don't print this message to the console if the operation was done
24366 	 * to a non-global zone.
24367 	 */
24368 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24369 		logflags |= SL_CONSOLE;
24370 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24371 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24372 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24373 	    acp->ac_start, acp->ac_end);
24374 }
24375 
24376 /*
24377  * Called inside tcp_rput when a message built using
24378  * tcp_ioctl_abort_build_msg is put into a queue.
24379  * Note that when we get here there is no wildcard in acp any more.
24380  */
24381 static void
24382 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24383 {
24384 	tcp_ioc_abort_conn_t *acp;
24385 
24386 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24387 	if (tcp->tcp_state <= acp->ac_end) {
24388 		/*
24389 		 * If we get here, we are already on the correct
24390 		 * squeue. This ioctl follows the following path
24391 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24392 		 * ->tcp_ioctl_abort->squeue_enter (if on a
24393 		 * different squeue)
24394 		 */
24395 		int errcode;
24396 
24397 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24398 		(void) tcp_clean_death(tcp, errcode, 26);
24399 	}
24400 	freemsg(mp);
24401 }
24402 
24403 /*
24404  * Abort all matching connections on a hash chain.
24405  */
24406 static int
24407 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24408     boolean_t exact, tcp_stack_t *tcps)
24409 {
24410 	int nmatch, err = 0;
24411 	tcp_t *tcp;
24412 	MBLKP mp, last, listhead = NULL;
24413 	conn_t	*tconnp;
24414 	connf_t	*connfp;
24415 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24416 
24417 	connfp = &ipst->ips_ipcl_conn_fanout[index];
24418 
24419 startover:
24420 	nmatch = 0;
24421 
24422 	mutex_enter(&connfp->connf_lock);
24423 	for (tconnp = connfp->connf_head; tconnp != NULL;
24424 	    tconnp = tconnp->conn_next) {
24425 		tcp = tconnp->conn_tcp;
24426 		if (TCP_AC_MATCH(acp, tcp)) {
24427 			CONN_INC_REF(tcp->tcp_connp);
24428 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24429 			if (mp == NULL) {
24430 				err = ENOMEM;
24431 				CONN_DEC_REF(tcp->tcp_connp);
24432 				break;
24433 			}
24434 			mp->b_prev = (mblk_t *)tcp;
24435 
24436 			if (listhead == NULL) {
24437 				listhead = mp;
24438 				last = mp;
24439 			} else {
24440 				last->b_next = mp;
24441 				last = mp;
24442 			}
24443 			nmatch++;
24444 			if (exact)
24445 				break;
24446 		}
24447 
24448 		/* Avoid holding lock for too long. */
24449 		if (nmatch >= 500)
24450 			break;
24451 	}
24452 	mutex_exit(&connfp->connf_lock);
24453 
24454 	/* Pass mp into the correct tcp */
24455 	while ((mp = listhead) != NULL) {
24456 		listhead = listhead->b_next;
24457 		tcp = (tcp_t *)mp->b_prev;
24458 		mp->b_next = mp->b_prev = NULL;
24459 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
24460 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
24461 	}
24462 
24463 	*count += nmatch;
24464 	if (nmatch >= 500 && err == 0)
24465 		goto startover;
24466 	return (err);
24467 }
24468 
24469 /*
24470  * Abort all connections that matches the attributes specified in acp.
24471  */
24472 static int
24473 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
24474 {
24475 	sa_family_t af;
24476 	uint32_t  ports;
24477 	uint16_t *pports;
24478 	int err = 0, count = 0;
24479 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24480 	int index = -1;
24481 	ushort_t logflags;
24482 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24483 
24484 	af = acp->ac_local.ss_family;
24485 
24486 	if (af == AF_INET) {
24487 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24488 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24489 			pports = (uint16_t *)&ports;
24490 			pports[1] = TCP_AC_V4LPORT(acp);
24491 			pports[0] = TCP_AC_V4RPORT(acp);
24492 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24493 		}
24494 	} else {
24495 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24496 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24497 			pports = (uint16_t *)&ports;
24498 			pports[1] = TCP_AC_V6LPORT(acp);
24499 			pports[0] = TCP_AC_V6RPORT(acp);
24500 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24501 		}
24502 	}
24503 
24504 	/*
24505 	 * For cases where remote addr, local port, and remote port are non-
24506 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24507 	 */
24508 	if (index != -1) {
24509 		err = tcp_ioctl_abort_bucket(acp, index,
24510 		    &count, exact, tcps);
24511 	} else {
24512 		/*
24513 		 * loop through all entries for wildcard case
24514 		 */
24515 		for (index = 0;
24516 		    index < ipst->ips_ipcl_conn_fanout_size;
24517 		    index++) {
24518 			err = tcp_ioctl_abort_bucket(acp, index,
24519 			    &count, exact, tcps);
24520 			if (err != 0)
24521 				break;
24522 		}
24523 	}
24524 
24525 	logflags = SL_TRACE | SL_NOTE;
24526 	/*
24527 	 * Don't print this message to the console if the operation was done
24528 	 * to a non-global zone.
24529 	 */
24530 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24531 		logflags |= SL_CONSOLE;
24532 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24533 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24534 	if (err == 0 && count == 0)
24535 		err = ENOENT;
24536 	return (err);
24537 }
24538 
24539 /*
24540  * Process the TCP_IOC_ABORT_CONN ioctl request.
24541  */
24542 static void
24543 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24544 {
24545 	int	err;
24546 	IOCP    iocp;
24547 	MBLKP   mp1;
24548 	sa_family_t laf, raf;
24549 	tcp_ioc_abort_conn_t *acp;
24550 	zone_t		*zptr;
24551 	conn_t		*connp = Q_TO_CONN(q);
24552 	zoneid_t	zoneid = connp->conn_zoneid;
24553 	tcp_t		*tcp = connp->conn_tcp;
24554 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24555 
24556 	iocp = (IOCP)mp->b_rptr;
24557 
24558 	if ((mp1 = mp->b_cont) == NULL ||
24559 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24560 		err = EINVAL;
24561 		goto out;
24562 	}
24563 
24564 	/* check permissions */
24565 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
24566 		err = EPERM;
24567 		goto out;
24568 	}
24569 
24570 	if (mp1->b_cont != NULL) {
24571 		freemsg(mp1->b_cont);
24572 		mp1->b_cont = NULL;
24573 	}
24574 
24575 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24576 	laf = acp->ac_local.ss_family;
24577 	raf = acp->ac_remote.ss_family;
24578 
24579 	/* check that a zone with the supplied zoneid exists */
24580 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24581 		zptr = zone_find_by_id(zoneid);
24582 		if (zptr != NULL) {
24583 			zone_rele(zptr);
24584 		} else {
24585 			err = EINVAL;
24586 			goto out;
24587 		}
24588 	}
24589 
24590 	/*
24591 	 * For exclusive stacks we set the zoneid to zero
24592 	 * to make TCP operate as if in the global zone.
24593 	 */
24594 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
24595 		acp->ac_zoneid = GLOBAL_ZONEID;
24596 
24597 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24598 	    acp->ac_start > acp->ac_end || laf != raf ||
24599 	    (laf != AF_INET && laf != AF_INET6)) {
24600 		err = EINVAL;
24601 		goto out;
24602 	}
24603 
24604 	tcp_ioctl_abort_dump(acp);
24605 	err = tcp_ioctl_abort(acp, tcps);
24606 
24607 out:
24608 	if (mp1 != NULL) {
24609 		freemsg(mp1);
24610 		mp->b_cont = NULL;
24611 	}
24612 
24613 	if (err != 0)
24614 		miocnak(q, mp, 0, err);
24615 	else
24616 		miocack(q, mp, 0, 0);
24617 }
24618 
24619 /*
24620  * tcp_time_wait_processing() handles processing of incoming packets when
24621  * the tcp is in the TIME_WAIT state.
24622  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24623  * on the time wait list.
24624  */
24625 void
24626 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24627     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24628 {
24629 	int32_t		bytes_acked;
24630 	int32_t		gap;
24631 	int32_t		rgap;
24632 	tcp_opt_t	tcpopt;
24633 	uint_t		flags;
24634 	uint32_t	new_swnd = 0;
24635 	conn_t		*connp;
24636 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24637 
24638 	BUMP_LOCAL(tcp->tcp_ibsegs);
24639 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
24640 
24641 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24642 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24643 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24644 	if (tcp->tcp_snd_ts_ok) {
24645 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24646 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24647 			    tcp->tcp_rnxt, TH_ACK);
24648 			goto done;
24649 		}
24650 	}
24651 	gap = seg_seq - tcp->tcp_rnxt;
24652 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24653 	if (gap < 0) {
24654 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
24655 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
24656 		    (seg_len > -gap ? -gap : seg_len));
24657 		seg_len += gap;
24658 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24659 			if (flags & TH_RST) {
24660 				goto done;
24661 			}
24662 			if ((flags & TH_FIN) && seg_len == -1) {
24663 				/*
24664 				 * When TCP receives a duplicate FIN in
24665 				 * TIME_WAIT state, restart the 2 MSL timer.
24666 				 * See page 73 in RFC 793. Make sure this TCP
24667 				 * is already on the TIME_WAIT list. If not,
24668 				 * just restart the timer.
24669 				 */
24670 				if (TCP_IS_DETACHED(tcp)) {
24671 					if (tcp_time_wait_remove(tcp, NULL) ==
24672 					    B_TRUE) {
24673 						tcp_time_wait_append(tcp);
24674 						TCP_DBGSTAT(tcps,
24675 						    tcp_rput_time_wait);
24676 					}
24677 				} else {
24678 					ASSERT(tcp != NULL);
24679 					TCP_TIMER_RESTART(tcp,
24680 					    tcps->tcps_time_wait_interval);
24681 				}
24682 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24683 				    tcp->tcp_rnxt, TH_ACK);
24684 				goto done;
24685 			}
24686 			flags |=  TH_ACK_NEEDED;
24687 			seg_len = 0;
24688 			goto process_ack;
24689 		}
24690 
24691 		/* Fix seg_seq, and chew the gap off the front. */
24692 		seg_seq = tcp->tcp_rnxt;
24693 	}
24694 
24695 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24696 		/*
24697 		 * Make sure that when we accept the connection, pick
24698 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24699 		 * old connection.
24700 		 *
24701 		 * The next ISS generated is equal to tcp_iss_incr_extra
24702 		 * + ISS_INCR/2 + other components depending on the
24703 		 * value of tcp_strong_iss.  We pre-calculate the new
24704 		 * ISS here and compare with tcp_snxt to determine if
24705 		 * we need to make adjustment to tcp_iss_incr_extra.
24706 		 *
24707 		 * The above calculation is ugly and is a
24708 		 * waste of CPU cycles...
24709 		 */
24710 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
24711 		int32_t adj;
24712 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24713 
24714 		switch (tcps->tcps_strong_iss) {
24715 		case 2: {
24716 			/* Add time and MD5 components. */
24717 			uint32_t answer[4];
24718 			struct {
24719 				uint32_t ports;
24720 				in6_addr_t src;
24721 				in6_addr_t dst;
24722 			} arg;
24723 			MD5_CTX context;
24724 
24725 			mutex_enter(&tcps->tcps_iss_key_lock);
24726 			context = tcps->tcps_iss_key;
24727 			mutex_exit(&tcps->tcps_iss_key_lock);
24728 			arg.ports = tcp->tcp_ports;
24729 			/* We use MAPPED addresses in tcp_iss_init */
24730 			arg.src = tcp->tcp_ip_src_v6;
24731 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24732 				IN6_IPADDR_TO_V4MAPPED(
24733 				    tcp->tcp_ipha->ipha_dst,
24734 				    &arg.dst);
24735 			} else {
24736 				arg.dst =
24737 				    tcp->tcp_ip6h->ip6_dst;
24738 			}
24739 			MD5Update(&context, (uchar_t *)&arg,
24740 			    sizeof (arg));
24741 			MD5Final((uchar_t *)answer, &context);
24742 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24743 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24744 			break;
24745 		}
24746 		case 1:
24747 			/* Add time component and min random (i.e. 1). */
24748 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24749 			break;
24750 		default:
24751 			/* Add only time component. */
24752 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24753 			break;
24754 		}
24755 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24756 			/*
24757 			 * New ISS not guaranteed to be ISS_INCR/2
24758 			 * ahead of the current tcp_snxt, so add the
24759 			 * difference to tcp_iss_incr_extra.
24760 			 */
24761 			tcps->tcps_iss_incr_extra += adj;
24762 		}
24763 		/*
24764 		 * If tcp_clean_death() can not perform the task now,
24765 		 * drop the SYN packet and let the other side re-xmit.
24766 		 * Otherwise pass the SYN packet back in, since the
24767 		 * old tcp state has been cleaned up or freed.
24768 		 */
24769 		if (tcp_clean_death(tcp, 0, 27) == -1)
24770 			goto done;
24771 		/*
24772 		 * We will come back to tcp_rput_data
24773 		 * on the global queue. Packets destined
24774 		 * for the global queue will be checked
24775 		 * with global policy. But the policy for
24776 		 * this packet has already been checked as
24777 		 * this was destined for the detached
24778 		 * connection. We need to bypass policy
24779 		 * check this time by attaching a dummy
24780 		 * ipsec_in with ipsec_in_dont_check set.
24781 		 */
24782 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
24783 		if (connp != NULL) {
24784 			TCP_STAT(tcps, tcp_time_wait_syn_success);
24785 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24786 			return;
24787 		}
24788 		goto done;
24789 	}
24790 
24791 	/*
24792 	 * rgap is the amount of stuff received out of window.  A negative
24793 	 * value is the amount out of window.
24794 	 */
24795 	if (rgap < 0) {
24796 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
24797 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
24798 		/* Fix seg_len and make sure there is something left. */
24799 		seg_len += rgap;
24800 		if (seg_len <= 0) {
24801 			if (flags & TH_RST) {
24802 				goto done;
24803 			}
24804 			flags |=  TH_ACK_NEEDED;
24805 			seg_len = 0;
24806 			goto process_ack;
24807 		}
24808 	}
24809 	/*
24810 	 * Check whether we can update tcp_ts_recent.  This test is
24811 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24812 	 * Extensions for High Performance: An Update", Internet Draft.
24813 	 */
24814 	if (tcp->tcp_snd_ts_ok &&
24815 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24816 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24817 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24818 		tcp->tcp_last_rcv_lbolt = lbolt64;
24819 	}
24820 
24821 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24822 		/* Always ack out of order packets */
24823 		flags |= TH_ACK_NEEDED;
24824 		seg_len = 0;
24825 	} else if (seg_len > 0) {
24826 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
24827 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
24828 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
24829 	}
24830 	if (flags & TH_RST) {
24831 		(void) tcp_clean_death(tcp, 0, 28);
24832 		goto done;
24833 	}
24834 	if (flags & TH_SYN) {
24835 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24836 		    TH_RST|TH_ACK);
24837 		/*
24838 		 * Do not delete the TCP structure if it is in
24839 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24840 		 */
24841 		goto done;
24842 	}
24843 process_ack:
24844 	if (flags & TH_ACK) {
24845 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24846 		if (bytes_acked <= 0) {
24847 			if (bytes_acked == 0 && seg_len == 0 &&
24848 			    new_swnd == tcp->tcp_swnd)
24849 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
24850 		} else {
24851 			/* Acks something not sent */
24852 			flags |= TH_ACK_NEEDED;
24853 		}
24854 	}
24855 	if (flags & TH_ACK_NEEDED) {
24856 		/*
24857 		 * Time to send an ack for some reason.
24858 		 */
24859 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24860 		    tcp->tcp_rnxt, TH_ACK);
24861 	}
24862 done:
24863 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24864 		DB_CKSUMSTART(mp) = 0;
24865 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24866 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
24867 	}
24868 	freemsg(mp);
24869 }
24870 
24871 /*
24872  * TCP Timers Implementation.
24873  */
24874 timeout_id_t
24875 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24876 {
24877 	mblk_t *mp;
24878 	tcp_timer_t *tcpt;
24879 	tcp_t *tcp = connp->conn_tcp;
24880 
24881 	ASSERT(connp->conn_sqp != NULL);
24882 
24883 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
24884 
24885 	if (tcp->tcp_timercache == NULL) {
24886 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24887 	} else {
24888 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
24889 		mp = tcp->tcp_timercache;
24890 		tcp->tcp_timercache = mp->b_next;
24891 		mp->b_next = NULL;
24892 		ASSERT(mp->b_wptr == NULL);
24893 	}
24894 
24895 	CONN_INC_REF(connp);
24896 	tcpt = (tcp_timer_t *)mp->b_rptr;
24897 	tcpt->connp = connp;
24898 	tcpt->tcpt_proc = f;
24899 	/*
24900 	 * TCP timers are normal timeouts. Plus, they do not require more than
24901 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
24902 	 * rounding up the expiration to the next resolution boundary, we can
24903 	 * batch timers in the callout subsystem to make TCP timers more
24904 	 * efficient. The roundup also protects short timers from expiring too
24905 	 * early before they have a chance to be cancelled.
24906 	 */
24907 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
24908 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
24909 
24910 	return ((timeout_id_t)mp);
24911 }
24912 
24913 static void
24914 tcp_timer_callback(void *arg)
24915 {
24916 	mblk_t *mp = (mblk_t *)arg;
24917 	tcp_timer_t *tcpt;
24918 	conn_t	*connp;
24919 
24920 	tcpt = (tcp_timer_t *)mp->b_rptr;
24921 	connp = tcpt->connp;
24922 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
24923 	    SQ_FILL, SQTAG_TCP_TIMER);
24924 }
24925 
24926 static void
24927 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24928 {
24929 	tcp_timer_t *tcpt;
24930 	conn_t *connp = (conn_t *)arg;
24931 	tcp_t *tcp = connp->conn_tcp;
24932 
24933 	tcpt = (tcp_timer_t *)mp->b_rptr;
24934 	ASSERT(connp == tcpt->connp);
24935 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24936 
24937 	/*
24938 	 * If the TCP has reached the closed state, don't proceed any
24939 	 * further. This TCP logically does not exist on the system.
24940 	 * tcpt_proc could for example access queues, that have already
24941 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24942 	 */
24943 	if (tcp->tcp_state != TCPS_CLOSED) {
24944 		(*tcpt->tcpt_proc)(connp);
24945 	} else {
24946 		tcp->tcp_timer_tid = 0;
24947 	}
24948 	tcp_timer_free(connp->conn_tcp, mp);
24949 }
24950 
24951 /*
24952  * There is potential race with untimeout and the handler firing at the same
24953  * time. The mblock may be freed by the handler while we are trying to use
24954  * it. But since both should execute on the same squeue, this race should not
24955  * occur.
24956  */
24957 clock_t
24958 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24959 {
24960 	mblk_t	*mp = (mblk_t *)id;
24961 	tcp_timer_t *tcpt;
24962 	clock_t delta;
24963 
24964 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
24965 
24966 	if (mp == NULL)
24967 		return (-1);
24968 
24969 	tcpt = (tcp_timer_t *)mp->b_rptr;
24970 	ASSERT(tcpt->connp == connp);
24971 
24972 	delta = untimeout_default(tcpt->tcpt_tid, 0);
24973 
24974 	if (delta >= 0) {
24975 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
24976 		tcp_timer_free(connp->conn_tcp, mp);
24977 		CONN_DEC_REF(connp);
24978 	}
24979 
24980 	return (delta);
24981 }
24982 
24983 /*
24984  * Allocate space for the timer event. The allocation looks like mblk, but it is
24985  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24986  *
24987  * Dealing with failures: If we can't allocate from the timer cache we try
24988  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24989  * points to b_rptr.
24990  * If we can't allocate anything using allocb_tryhard(), we perform a last
24991  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24992  * save the actual allocation size in b_datap.
24993  */
24994 mblk_t *
24995 tcp_timermp_alloc(int kmflags)
24996 {
24997 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
24998 	    kmflags & ~KM_PANIC);
24999 
25000 	if (mp != NULL) {
25001 		mp->b_next = mp->b_prev = NULL;
25002 		mp->b_rptr = (uchar_t *)(&mp[1]);
25003 		mp->b_wptr = NULL;
25004 		mp->b_datap = NULL;
25005 		mp->b_queue = NULL;
25006 		mp->b_cont = NULL;
25007 	} else if (kmflags & KM_PANIC) {
25008 		/*
25009 		 * Failed to allocate memory for the timer. Try allocating from
25010 		 * dblock caches.
25011 		 */
25012 		/* ipclassifier calls this from a constructor - hence no tcps */
25013 		TCP_G_STAT(tcp_timermp_allocfail);
25014 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25015 		if (mp == NULL) {
25016 			size_t size = 0;
25017 			/*
25018 			 * Memory is really low. Try tryhard allocation.
25019 			 *
25020 			 * ipclassifier calls this from a constructor -
25021 			 * hence no tcps
25022 			 */
25023 			TCP_G_STAT(tcp_timermp_allocdblfail);
25024 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25025 			    sizeof (tcp_timer_t), &size, kmflags);
25026 			mp->b_rptr = (uchar_t *)(&mp[1]);
25027 			mp->b_next = mp->b_prev = NULL;
25028 			mp->b_wptr = (uchar_t *)-1;
25029 			mp->b_datap = (dblk_t *)size;
25030 			mp->b_queue = NULL;
25031 			mp->b_cont = NULL;
25032 		}
25033 		ASSERT(mp->b_wptr != NULL);
25034 	}
25035 	/* ipclassifier calls this from a constructor - hence no tcps */
25036 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25037 
25038 	return (mp);
25039 }
25040 
25041 /*
25042  * Free per-tcp timer cache.
25043  * It can only contain entries from tcp_timercache.
25044  */
25045 void
25046 tcp_timermp_free(tcp_t *tcp)
25047 {
25048 	mblk_t *mp;
25049 
25050 	while ((mp = tcp->tcp_timercache) != NULL) {
25051 		ASSERT(mp->b_wptr == NULL);
25052 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25053 		kmem_cache_free(tcp_timercache, mp);
25054 	}
25055 }
25056 
25057 /*
25058  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25059  * events there already (currently at most two events are cached).
25060  * If the event is not allocated from the timer cache, free it right away.
25061  */
25062 static void
25063 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25064 {
25065 	mblk_t *mp1 = tcp->tcp_timercache;
25066 
25067 	if (mp->b_wptr != NULL) {
25068 		/*
25069 		 * This allocation is not from a timer cache, free it right
25070 		 * away.
25071 		 */
25072 		if (mp->b_wptr != (uchar_t *)-1)
25073 			freeb(mp);
25074 		else
25075 			kmem_free(mp, (size_t)mp->b_datap);
25076 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25077 		/* Cache this timer block for future allocations */
25078 		mp->b_rptr = (uchar_t *)(&mp[1]);
25079 		mp->b_next = mp1;
25080 		tcp->tcp_timercache = mp;
25081 	} else {
25082 		kmem_cache_free(tcp_timercache, mp);
25083 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25084 	}
25085 }
25086 
25087 /*
25088  * End of TCP Timers implementation.
25089  */
25090 
25091 /*
25092  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25093  * on the specified backing STREAMS q. Note, the caller may make the
25094  * decision to call based on the tcp_t.tcp_flow_stopped value which
25095  * when check outside the q's lock is only an advisory check ...
25096  */
25097 void
25098 tcp_setqfull(tcp_t *tcp)
25099 {
25100 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25101 	conn_t	*connp = tcp->tcp_connp;
25102 
25103 	if (tcp->tcp_closed)
25104 		return;
25105 
25106 	if (IPCL_IS_NONSTR(connp)) {
25107 		(*connp->conn_upcalls->su_txq_full)
25108 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25109 		tcp->tcp_flow_stopped = B_TRUE;
25110 	} else {
25111 		queue_t *q = tcp->tcp_wq;
25112 
25113 		if (!(q->q_flag & QFULL)) {
25114 			mutex_enter(QLOCK(q));
25115 			if (!(q->q_flag & QFULL)) {
25116 				/* still need to set QFULL */
25117 				q->q_flag |= QFULL;
25118 				tcp->tcp_flow_stopped = B_TRUE;
25119 				mutex_exit(QLOCK(q));
25120 				TCP_STAT(tcps, tcp_flwctl_on);
25121 			} else {
25122 				mutex_exit(QLOCK(q));
25123 			}
25124 		}
25125 	}
25126 }
25127 
25128 void
25129 tcp_clrqfull(tcp_t *tcp)
25130 {
25131 	conn_t  *connp = tcp->tcp_connp;
25132 
25133 	if (tcp->tcp_closed)
25134 		return;
25135 
25136 	if (IPCL_IS_NONSTR(connp)) {
25137 		(*connp->conn_upcalls->su_txq_full)
25138 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25139 		tcp->tcp_flow_stopped = B_FALSE;
25140 	} else {
25141 		queue_t *q = tcp->tcp_wq;
25142 
25143 		if (q->q_flag & QFULL) {
25144 			mutex_enter(QLOCK(q));
25145 			if (q->q_flag & QFULL) {
25146 				q->q_flag &= ~QFULL;
25147 				tcp->tcp_flow_stopped = B_FALSE;
25148 				mutex_exit(QLOCK(q));
25149 				if (q->q_flag & QWANTW)
25150 					qbackenable(q, 0);
25151 			} else {
25152 				mutex_exit(QLOCK(q));
25153 			}
25154 		}
25155 	}
25156 }
25157 
25158 /*
25159  * kstats related to squeues i.e. not per IP instance
25160  */
25161 static void *
25162 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
25163 {
25164 	kstat_t *ksp;
25165 
25166 	tcp_g_stat_t template = {
25167 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
25168 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
25169 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
25170 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
25171 	};
25172 
25173 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
25174 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25175 	    KSTAT_FLAG_VIRTUAL);
25176 
25177 	if (ksp == NULL)
25178 		return (NULL);
25179 
25180 	bcopy(&template, tcp_g_statp, sizeof (template));
25181 	ksp->ks_data = (void *)tcp_g_statp;
25182 
25183 	kstat_install(ksp);
25184 	return (ksp);
25185 }
25186 
25187 static void
25188 tcp_g_kstat_fini(kstat_t *ksp)
25189 {
25190 	if (ksp != NULL) {
25191 		kstat_delete(ksp);
25192 	}
25193 }
25194 
25195 
25196 static void *
25197 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
25198 {
25199 	kstat_t *ksp;
25200 
25201 	tcp_stat_t template = {
25202 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
25203 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
25204 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
25205 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
25206 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
25207 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
25208 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
25209 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
25210 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
25211 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
25212 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
25213 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
25214 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
25215 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
25216 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
25217 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
25218 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
25219 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
25220 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
25221 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
25222 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
25223 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
25224 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
25225 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
25226 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
25227 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
25228 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
25229 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
25230 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
25231 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
25232 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
25233 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
25234 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
25235 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
25236 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
25237 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
25238 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
25239 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
25240 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
25241 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
25242 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
25243 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
25244 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
25245 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
25246 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
25247 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
25248 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
25249 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
25250 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
25251 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
25252 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
25253 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
25254 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
25255 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
25256 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
25257 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
25258 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
25259 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
25260 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
25261 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
25262 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
25263 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
25264 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
25265 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
25266 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
25267 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
25268 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
25269 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
25270 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
25271 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
25272 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
25273 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
25274 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
25275 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
25276 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
25277 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
25278 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
25279 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
25280 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
25281 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
25282 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
25283 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
25284 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
25285 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
25286 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
25287 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
25288 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
25289 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
25290 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
25291 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
25292 	};
25293 
25294 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
25295 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25296 	    KSTAT_FLAG_VIRTUAL, stackid);
25297 
25298 	if (ksp == NULL)
25299 		return (NULL);
25300 
25301 	bcopy(&template, tcps_statisticsp, sizeof (template));
25302 	ksp->ks_data = (void *)tcps_statisticsp;
25303 	ksp->ks_private = (void *)(uintptr_t)stackid;
25304 
25305 	kstat_install(ksp);
25306 	return (ksp);
25307 }
25308 
25309 static void
25310 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
25311 {
25312 	if (ksp != NULL) {
25313 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25314 		kstat_delete_netstack(ksp, stackid);
25315 	}
25316 }
25317 
25318 /*
25319  * TCP Kstats implementation
25320  */
25321 static void *
25322 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
25323 {
25324 	kstat_t	*ksp;
25325 
25326 	tcp_named_kstat_t template = {
25327 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25328 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25329 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25330 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25331 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25332 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25333 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25334 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25335 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25336 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25337 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25338 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25339 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25340 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25341 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25342 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25343 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25344 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25345 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25346 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25347 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25348 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25349 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25350 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25351 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25352 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25353 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25354 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25355 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25356 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25357 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25358 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25359 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25360 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25361 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25362 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25363 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25364 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25365 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25366 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25367 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25368 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25369 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25370 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25371 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25372 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25373 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25374 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25375 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25376 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25377 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25378 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25379 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25380 	};
25381 
25382 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
25383 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
25384 
25385 	if (ksp == NULL)
25386 		return (NULL);
25387 
25388 	template.rtoAlgorithm.value.ui32 = 4;
25389 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
25390 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
25391 	template.maxConn.value.i32 = -1;
25392 
25393 	bcopy(&template, ksp->ks_data, sizeof (template));
25394 	ksp->ks_update = tcp_kstat_update;
25395 	ksp->ks_private = (void *)(uintptr_t)stackid;
25396 
25397 	kstat_install(ksp);
25398 	return (ksp);
25399 }
25400 
25401 static void
25402 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
25403 {
25404 	if (ksp != NULL) {
25405 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25406 		kstat_delete_netstack(ksp, stackid);
25407 	}
25408 }
25409 
25410 static int
25411 tcp_kstat_update(kstat_t *kp, int rw)
25412 {
25413 	tcp_named_kstat_t *tcpkp;
25414 	tcp_t		*tcp;
25415 	connf_t		*connfp;
25416 	conn_t		*connp;
25417 	int 		i;
25418 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
25419 	netstack_t	*ns;
25420 	tcp_stack_t	*tcps;
25421 	ip_stack_t	*ipst;
25422 
25423 	if ((kp == NULL) || (kp->ks_data == NULL))
25424 		return (EIO);
25425 
25426 	if (rw == KSTAT_WRITE)
25427 		return (EACCES);
25428 
25429 	ns = netstack_find_by_stackid(stackid);
25430 	if (ns == NULL)
25431 		return (-1);
25432 	tcps = ns->netstack_tcp;
25433 	if (tcps == NULL) {
25434 		netstack_rele(ns);
25435 		return (-1);
25436 	}
25437 
25438 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25439 
25440 	tcpkp->currEstab.value.ui32 = 0;
25441 
25442 	ipst = ns->netstack_ip;
25443 
25444 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25445 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25446 		connp = NULL;
25447 		while ((connp =
25448 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25449 			tcp = connp->conn_tcp;
25450 			switch (tcp_snmp_state(tcp)) {
25451 			case MIB2_TCP_established:
25452 			case MIB2_TCP_closeWait:
25453 				tcpkp->currEstab.value.ui32++;
25454 				break;
25455 			}
25456 		}
25457 	}
25458 
25459 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
25460 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
25461 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
25462 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
25463 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
25464 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
25465 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
25466 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
25467 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
25468 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
25469 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
25470 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
25471 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
25472 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
25473 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
25474 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
25475 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
25476 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
25477 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
25478 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
25479 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
25480 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
25481 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
25482 	tcpkp->inDataInorderSegs.value.ui32 =
25483 	    tcps->tcps_mib.tcpInDataInorderSegs;
25484 	tcpkp->inDataInorderBytes.value.ui32 =
25485 	    tcps->tcps_mib.tcpInDataInorderBytes;
25486 	tcpkp->inDataUnorderSegs.value.ui32 =
25487 	    tcps->tcps_mib.tcpInDataUnorderSegs;
25488 	tcpkp->inDataUnorderBytes.value.ui32 =
25489 	    tcps->tcps_mib.tcpInDataUnorderBytes;
25490 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
25491 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
25492 	tcpkp->inDataPartDupSegs.value.ui32 =
25493 	    tcps->tcps_mib.tcpInDataPartDupSegs;
25494 	tcpkp->inDataPartDupBytes.value.ui32 =
25495 	    tcps->tcps_mib.tcpInDataPartDupBytes;
25496 	tcpkp->inDataPastWinSegs.value.ui32 =
25497 	    tcps->tcps_mib.tcpInDataPastWinSegs;
25498 	tcpkp->inDataPastWinBytes.value.ui32 =
25499 	    tcps->tcps_mib.tcpInDataPastWinBytes;
25500 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
25501 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
25502 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
25503 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
25504 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
25505 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
25506 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
25507 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
25508 	tcpkp->timKeepaliveProbe.value.ui32 =
25509 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
25510 	tcpkp->timKeepaliveDrop.value.ui32 =
25511 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
25512 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
25513 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
25514 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
25515 	tcpkp->outSackRetransSegs.value.ui32 =
25516 	    tcps->tcps_mib.tcpOutSackRetransSegs;
25517 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
25518 
25519 	netstack_rele(ns);
25520 	return (0);
25521 }
25522 
25523 void
25524 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25525 {
25526 	uint16_t	hdr_len;
25527 	ipha_t		*ipha;
25528 	uint8_t		*nexthdrp;
25529 	tcph_t		*tcph;
25530 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
25531 
25532 	/* Already has an eager */
25533 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25534 		TCP_STAT(tcps, tcp_reinput_syn);
25535 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25536 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
25537 		return;
25538 	}
25539 
25540 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25541 	case IPV4_VERSION:
25542 		ipha = (ipha_t *)mp->b_rptr;
25543 		hdr_len = IPH_HDR_LENGTH(ipha);
25544 		break;
25545 	case IPV6_VERSION:
25546 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25547 		    &hdr_len, &nexthdrp)) {
25548 			CONN_DEC_REF(connp);
25549 			freemsg(mp);
25550 			return;
25551 		}
25552 		break;
25553 	}
25554 
25555 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25556 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25557 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25558 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25559 	}
25560 
25561 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25562 	    SQ_FILL, SQTAG_TCP_REINPUT);
25563 }
25564 
25565 static int
25566 tcp_squeue_switch(int val)
25567 {
25568 	int rval = SQ_FILL;
25569 
25570 	switch (val) {
25571 	case 1:
25572 		rval = SQ_NODRAIN;
25573 		break;
25574 	case 2:
25575 		rval = SQ_PROCESS;
25576 		break;
25577 	default:
25578 		break;
25579 	}
25580 	return (rval);
25581 }
25582 
25583 /*
25584  * This is called once for each squeue - globally for all stack
25585  * instances.
25586  */
25587 static void
25588 tcp_squeue_add(squeue_t *sqp)
25589 {
25590 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25591 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
25592 
25593 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25594 	tcp_time_wait->tcp_time_wait_tid =
25595 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
25596 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
25597 	    CALLOUT_FLAG_ROUNDUP);
25598 	if (tcp_free_list_max_cnt == 0) {
25599 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25600 		    max_ncpus : boot_max_ncpus);
25601 
25602 		/*
25603 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25604 		 */
25605 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25606 		    (tcp_ncpus * sizeof (tcp_t) * 100);
25607 	}
25608 	tcp_time_wait->tcp_free_list_cnt = 0;
25609 }
25610 
25611 static int
25612 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
25613 {
25614 	mblk_t	*ire_mp = NULL;
25615 	mblk_t	*syn_mp;
25616 	mblk_t	*mdti;
25617 	mblk_t	*lsoi;
25618 	int	retval;
25619 	tcph_t	*tcph;
25620 	cred_t	*ecr;
25621 	ts_label_t	*tsl;
25622 	uint32_t	mss;
25623 	conn_t	*connp = tcp->tcp_connp;
25624 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25625 
25626 	if (error == 0) {
25627 		/*
25628 		 * Adapt Multidata information, if any.  The
25629 		 * following tcp_mdt_update routine will free
25630 		 * the message.
25631 		 */
25632 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
25633 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
25634 			    b_rptr)->mdt_capab, B_TRUE);
25635 			freemsg(mdti);
25636 		}
25637 
25638 		/*
25639 		 * Check to update LSO information with tcp, and
25640 		 * tcp_lso_update routine will free the message.
25641 		 */
25642 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
25643 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
25644 			    b_rptr)->lso_capab);
25645 			freemsg(lsoi);
25646 		}
25647 
25648 		/* Get the IRE, if we had requested for it */
25649 		if (mp != NULL)
25650 			ire_mp = tcp_ire_mp(&mp);
25651 
25652 		if (tcp->tcp_hard_binding) {
25653 			tcp->tcp_hard_binding = B_FALSE;
25654 			tcp->tcp_hard_bound = B_TRUE;
25655 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
25656 			if (retval != 0) {
25657 				error = EADDRINUSE;
25658 				goto bind_failed;
25659 			}
25660 		} else {
25661 			if (ire_mp != NULL)
25662 				freeb(ire_mp);
25663 			goto after_syn_sent;
25664 		}
25665 
25666 		retval = tcp_adapt_ire(tcp, ire_mp);
25667 		if (ire_mp != NULL)
25668 			freeb(ire_mp);
25669 		if (retval == 0) {
25670 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
25671 			    ENETUNREACH : EADDRNOTAVAIL);
25672 			goto ipcl_rm;
25673 		}
25674 		/*
25675 		 * Don't let an endpoint connect to itself.
25676 		 * Also checked in tcp_connect() but that
25677 		 * check can't handle the case when the
25678 		 * local IP address is INADDR_ANY.
25679 		 */
25680 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25681 			if ((tcp->tcp_ipha->ipha_dst ==
25682 			    tcp->tcp_ipha->ipha_src) &&
25683 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25684 			    tcp->tcp_tcph->th_fport))) {
25685 				error = EADDRNOTAVAIL;
25686 				goto ipcl_rm;
25687 			}
25688 		} else {
25689 			if (IN6_ARE_ADDR_EQUAL(
25690 			    &tcp->tcp_ip6h->ip6_dst,
25691 			    &tcp->tcp_ip6h->ip6_src) &&
25692 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25693 			    tcp->tcp_tcph->th_fport))) {
25694 				error = EADDRNOTAVAIL;
25695 				goto ipcl_rm;
25696 			}
25697 		}
25698 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
25699 		/*
25700 		 * This should not be possible!  Just for
25701 		 * defensive coding...
25702 		 */
25703 		if (tcp->tcp_state != TCPS_SYN_SENT)
25704 			goto after_syn_sent;
25705 
25706 		if (is_system_labeled() &&
25707 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
25708 			error = EHOSTUNREACH;
25709 			goto ipcl_rm;
25710 		}
25711 
25712 		/*
25713 		 * tcp_adapt_ire() does not adjust
25714 		 * for TCP/IP header length.
25715 		 */
25716 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
25717 
25718 		/*
25719 		 * Just make sure our rwnd is at
25720 		 * least tcp_recv_hiwat_mss * MSS
25721 		 * large, and round up to the nearest
25722 		 * MSS.
25723 		 *
25724 		 * We do the round up here because
25725 		 * we need to get the interface
25726 		 * MTU first before we can do the
25727 		 * round up.
25728 		 */
25729 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
25730 		    tcps->tcps_recv_hiwat_minmss * mss);
25731 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
25732 		tcp_set_ws_value(tcp);
25733 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
25734 		    tcp->tcp_tcph->th_win);
25735 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
25736 			tcp->tcp_snd_ws_ok = B_TRUE;
25737 
25738 		/*
25739 		 * Set tcp_snd_ts_ok to true
25740 		 * so that tcp_xmit_mp will
25741 		 * include the timestamp
25742 		 * option in the SYN segment.
25743 		 */
25744 		if (tcps->tcps_tstamp_always ||
25745 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
25746 			tcp->tcp_snd_ts_ok = B_TRUE;
25747 		}
25748 
25749 		/*
25750 		 * tcp_snd_sack_ok can be set in
25751 		 * tcp_adapt_ire() if the sack metric
25752 		 * is set.  So check it here also.
25753 		 */
25754 		if (tcps->tcps_sack_permitted == 2 ||
25755 		    tcp->tcp_snd_sack_ok) {
25756 			if (tcp->tcp_sack_info == NULL) {
25757 				tcp->tcp_sack_info =
25758 				    kmem_cache_alloc(tcp_sack_info_cache,
25759 				    KM_SLEEP);
25760 			}
25761 			tcp->tcp_snd_sack_ok = B_TRUE;
25762 		}
25763 
25764 		/*
25765 		 * Should we use ECN?  Note that the current
25766 		 * default value (SunOS 5.9) of tcp_ecn_permitted
25767 		 * is 1.  The reason for doing this is that there
25768 		 * are equipments out there that will drop ECN
25769 		 * enabled IP packets.  Setting it to 1 avoids
25770 		 * compatibility problems.
25771 		 */
25772 		if (tcps->tcps_ecn_permitted == 2)
25773 			tcp->tcp_ecn_ok = B_TRUE;
25774 
25775 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
25776 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
25777 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
25778 		if (syn_mp) {
25779 			/*
25780 			 * cr contains the cred from the thread calling
25781 			 * connect().
25782 			 *
25783 			 * If no thread cred is available, use the
25784 			 * socket creator's cred instead. If still no
25785 			 * cred, drop the request rather than risk a
25786 			 * panic on production systems.
25787 			 */
25788 			if (cr == NULL) {
25789 				cr = CONN_CRED(connp);
25790 				pid = tcp->tcp_cpid;
25791 				ASSERT(cr != NULL);
25792 				if (cr != NULL) {
25793 					mblk_setcred(syn_mp, cr, pid);
25794 				} else {
25795 					error = ECONNABORTED;
25796 					goto ipcl_rm;
25797 				}
25798 
25799 			/*
25800 			 * If an effective security label exists for
25801 			 * the connection, create a copy of the thread's
25802 			 * cred but with the effective label attached.
25803 			 */
25804 			} else if (is_system_labeled() &&
25805 			    connp->conn_effective_cred != NULL &&
25806 			    (tsl = crgetlabel(connp->
25807 			    conn_effective_cred)) != NULL) {
25808 				if ((ecr = copycred_from_tslabel(cr,
25809 				    tsl, KM_NOSLEEP)) == NULL) {
25810 					error = ENOMEM;
25811 					goto ipcl_rm;
25812 				}
25813 				mblk_setcred(syn_mp, ecr, pid);
25814 				crfree(ecr);
25815 
25816 			/*
25817 			 * Default to using the thread's cred unchanged.
25818 			 */
25819 			} else {
25820 				mblk_setcred(syn_mp, cr, pid);
25821 			}
25822 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
25823 		}
25824 	after_syn_sent:
25825 		if (mp != NULL) {
25826 			ASSERT(mp->b_cont == NULL);
25827 			freeb(mp);
25828 		}
25829 		return (error);
25830 	} else {
25831 		/* error */
25832 		if (tcp->tcp_debug) {
25833 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
25834 			    "tcp_post_ip_bind: error == %d", error);
25835 		}
25836 		if (mp != NULL) {
25837 			freeb(mp);
25838 		}
25839 	}
25840 
25841 ipcl_rm:
25842 	/*
25843 	 * Need to unbind with classifier since we were just
25844 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
25845 	 */
25846 	tcp->tcp_hard_bound = B_FALSE;
25847 	tcp->tcp_hard_binding = B_FALSE;
25848 
25849 	ipcl_hash_remove(connp);
25850 
25851 bind_failed:
25852 	tcp->tcp_state = TCPS_IDLE;
25853 	if (tcp->tcp_ipversion == IPV4_VERSION)
25854 		tcp->tcp_ipha->ipha_src = 0;
25855 	else
25856 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
25857 	/*
25858 	 * Copy of the src addr. in tcp_t is needed since
25859 	 * the lookup funcs. can only look at tcp_t
25860 	 */
25861 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
25862 
25863 	tcph = tcp->tcp_tcph;
25864 	tcph->th_lport[0] = 0;
25865 	tcph->th_lport[1] = 0;
25866 	tcp_bind_hash_remove(tcp);
25867 	bzero(&connp->u_port, sizeof (connp->u_port));
25868 	/* blow away saved option results if any */
25869 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
25870 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
25871 
25872 	conn_delete_ire(tcp->tcp_connp, NULL);
25873 
25874 	return (error);
25875 }
25876 
25877 static int
25878 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
25879     boolean_t bind_to_req_port_only, cred_t *cr)
25880 {
25881 	in_port_t	mlp_port;
25882 	mlp_type_t 	addrtype, mlptype;
25883 	boolean_t	user_specified;
25884 	in_port_t	allocated_port;
25885 	in_port_t	requested_port = *requested_port_ptr;
25886 	conn_t		*connp;
25887 	zone_t		*zone;
25888 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25889 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
25890 
25891 	/*
25892 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
25893 	 */
25894 	if (cr == NULL)
25895 		cr = tcp->tcp_cred;
25896 	/*
25897 	 * Get a valid port (within the anonymous range and should not
25898 	 * be a privileged one) to use if the user has not given a port.
25899 	 * If multiple threads are here, they may all start with
25900 	 * with the same initial port. But, it should be fine as long as
25901 	 * tcp_bindi will ensure that no two threads will be assigned
25902 	 * the same port.
25903 	 *
25904 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
25905 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
25906 	 * unless TCP_ANONPRIVBIND option is set.
25907 	 */
25908 	mlptype = mlptSingle;
25909 	mlp_port = requested_port;
25910 	if (requested_port == 0) {
25911 		requested_port = tcp->tcp_anon_priv_bind ?
25912 		    tcp_get_next_priv_port(tcp) :
25913 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
25914 		    tcp, B_TRUE);
25915 		if (requested_port == 0) {
25916 			return (-TNOADDR);
25917 		}
25918 		user_specified = B_FALSE;
25919 
25920 		/*
25921 		 * If the user went through one of the RPC interfaces to create
25922 		 * this socket and RPC is MLP in this zone, then give him an
25923 		 * anonymous MLP.
25924 		 */
25925 		connp = tcp->tcp_connp;
25926 		if (connp->conn_anon_mlp && is_system_labeled()) {
25927 			zone = crgetzone(cr);
25928 			addrtype = tsol_mlp_addr_type(
25929 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
25930 			    IPV6_VERSION, &v6addr,
25931 			    tcps->tcps_netstack->netstack_ip);
25932 			if (addrtype == mlptSingle) {
25933 				return (-TNOADDR);
25934 			}
25935 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25936 			    PMAPPORT, addrtype);
25937 			mlp_port = PMAPPORT;
25938 		}
25939 	} else {
25940 		int i;
25941 		boolean_t priv = B_FALSE;
25942 
25943 		/*
25944 		 * If the requested_port is in the well-known privileged range,
25945 		 * verify that the stream was opened by a privileged user.
25946 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
25947 		 * but instead the code relies on:
25948 		 * - the fact that the address of the array and its size never
25949 		 *   changes
25950 		 * - the atomic assignment of the elements of the array
25951 		 */
25952 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
25953 			priv = B_TRUE;
25954 		} else {
25955 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
25956 				if (requested_port ==
25957 				    tcps->tcps_g_epriv_ports[i]) {
25958 					priv = B_TRUE;
25959 					break;
25960 				}
25961 			}
25962 		}
25963 		if (priv) {
25964 			if (secpolicy_net_privaddr(cr, requested_port,
25965 			    IPPROTO_TCP) != 0) {
25966 				if (tcp->tcp_debug) {
25967 					(void) strlog(TCP_MOD_ID, 0, 1,
25968 					    SL_ERROR|SL_TRACE,
25969 					    "tcp_bind: no priv for port %d",
25970 					    requested_port);
25971 				}
25972 				return (-TACCES);
25973 			}
25974 		}
25975 		user_specified = B_TRUE;
25976 
25977 		connp = tcp->tcp_connp;
25978 		if (is_system_labeled()) {
25979 			zone = crgetzone(cr);
25980 			addrtype = tsol_mlp_addr_type(
25981 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
25982 			    IPV6_VERSION, &v6addr,
25983 			    tcps->tcps_netstack->netstack_ip);
25984 			if (addrtype == mlptSingle) {
25985 				return (-TNOADDR);
25986 			}
25987 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25988 			    requested_port, addrtype);
25989 		}
25990 	}
25991 
25992 	if (mlptype != mlptSingle) {
25993 		if (secpolicy_net_bindmlp(cr) != 0) {
25994 			if (tcp->tcp_debug) {
25995 				(void) strlog(TCP_MOD_ID, 0, 1,
25996 				    SL_ERROR|SL_TRACE,
25997 				    "tcp_bind: no priv for multilevel port %d",
25998 				    requested_port);
25999 			}
26000 			return (-TACCES);
26001 		}
26002 
26003 		/*
26004 		 * If we're specifically binding a shared IP address and the
26005 		 * port is MLP on shared addresses, then check to see if this
26006 		 * zone actually owns the MLP.  Reject if not.
26007 		 */
26008 		if (mlptype == mlptShared && addrtype == mlptShared) {
26009 			/*
26010 			 * No need to handle exclusive-stack zones since
26011 			 * ALL_ZONES only applies to the shared stack.
26012 			 */
26013 			zoneid_t mlpzone;
26014 
26015 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26016 			    htons(mlp_port));
26017 			if (connp->conn_zoneid != mlpzone) {
26018 				if (tcp->tcp_debug) {
26019 					(void) strlog(TCP_MOD_ID, 0, 1,
26020 					    SL_ERROR|SL_TRACE,
26021 					    "tcp_bind: attempt to bind port "
26022 					    "%d on shared addr in zone %d "
26023 					    "(should be %d)",
26024 					    mlp_port, connp->conn_zoneid,
26025 					    mlpzone);
26026 				}
26027 				return (-TACCES);
26028 			}
26029 		}
26030 
26031 		if (!user_specified) {
26032 			int err;
26033 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26034 			    requested_port, B_TRUE);
26035 			if (err != 0) {
26036 				if (tcp->tcp_debug) {
26037 					(void) strlog(TCP_MOD_ID, 0, 1,
26038 					    SL_ERROR|SL_TRACE,
26039 					    "tcp_bind: cannot establish anon "
26040 					    "MLP for port %d",
26041 					    requested_port);
26042 				}
26043 				return (err);
26044 			}
26045 			connp->conn_anon_port = B_TRUE;
26046 		}
26047 		connp->conn_mlp_type = mlptype;
26048 	}
26049 
26050 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26051 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26052 
26053 	if (allocated_port == 0) {
26054 		connp->conn_mlp_type = mlptSingle;
26055 		if (connp->conn_anon_port) {
26056 			connp->conn_anon_port = B_FALSE;
26057 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26058 			    requested_port, B_FALSE);
26059 		}
26060 		if (bind_to_req_port_only) {
26061 			if (tcp->tcp_debug) {
26062 				(void) strlog(TCP_MOD_ID, 0, 1,
26063 				    SL_ERROR|SL_TRACE,
26064 				    "tcp_bind: requested addr busy");
26065 			}
26066 			return (-TADDRBUSY);
26067 		} else {
26068 			/* If we are out of ports, fail the bind. */
26069 			if (tcp->tcp_debug) {
26070 				(void) strlog(TCP_MOD_ID, 0, 1,
26071 				    SL_ERROR|SL_TRACE,
26072 				    "tcp_bind: out of ports?");
26073 			}
26074 			return (-TNOADDR);
26075 		}
26076 	}
26077 
26078 	/* Pass the allocated port back */
26079 	*requested_port_ptr = allocated_port;
26080 	return (0);
26081 }
26082 
26083 static int
26084 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26085     boolean_t bind_to_req_port_only)
26086 {
26087 	tcp_t	*tcp = connp->conn_tcp;
26088 	sin_t	*sin;
26089 	sin6_t  *sin6;
26090 	in_port_t requested_port;
26091 	ipaddr_t	v4addr;
26092 	in6_addr_t	v6addr;
26093 	uint_t	origipversion;
26094 	int	error = 0;
26095 
26096 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26097 
26098 	if (tcp->tcp_state == TCPS_BOUND) {
26099 		return (0);
26100 	} else if (tcp->tcp_state > TCPS_BOUND) {
26101 		if (tcp->tcp_debug) {
26102 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26103 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26104 		}
26105 		return (-TOUTSTATE);
26106 	}
26107 	origipversion = tcp->tcp_ipversion;
26108 
26109 	ASSERT(sa != NULL && len != 0);
26110 
26111 	if (!OK_32PTR((char *)sa)) {
26112 		if (tcp->tcp_debug) {
26113 			(void) strlog(TCP_MOD_ID, 0, 1,
26114 			    SL_ERROR|SL_TRACE,
26115 			    "tcp_bind: bad address parameter, "
26116 			    "address %p, len %d",
26117 			    (void *)sa, len);
26118 		}
26119 		return (-TPROTO);
26120 	}
26121 
26122 	switch (len) {
26123 	case sizeof (sin_t):	/* Complete IPv4 address */
26124 		sin = (sin_t *)sa;
26125 		/*
26126 		 * With sockets sockfs will accept bogus sin_family in
26127 		 * bind() and replace it with the family used in the socket
26128 		 * call.
26129 		 */
26130 		if (sin->sin_family != AF_INET ||
26131 		    tcp->tcp_family != AF_INET) {
26132 			return (EAFNOSUPPORT);
26133 		}
26134 		requested_port = ntohs(sin->sin_port);
26135 		tcp->tcp_ipversion = IPV4_VERSION;
26136 		v4addr = sin->sin_addr.s_addr;
26137 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26138 		break;
26139 
26140 	case sizeof (sin6_t): /* Complete IPv6 address */
26141 		sin6 = (sin6_t *)sa;
26142 		if (sin6->sin6_family != AF_INET6 ||
26143 		    tcp->tcp_family != AF_INET6) {
26144 			return (EAFNOSUPPORT);
26145 		}
26146 		requested_port = ntohs(sin6->sin6_port);
26147 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26148 		    IPV4_VERSION : IPV6_VERSION;
26149 		v6addr = sin6->sin6_addr;
26150 		break;
26151 
26152 	default:
26153 		if (tcp->tcp_debug) {
26154 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26155 			    "tcp_bind: bad address length, %d", len);
26156 		}
26157 		return (EAFNOSUPPORT);
26158 		/* return (-TBADADDR); */
26159 	}
26160 
26161 	tcp->tcp_bound_source_v6 = v6addr;
26162 
26163 	/* Check for change in ipversion */
26164 	if (origipversion != tcp->tcp_ipversion) {
26165 		ASSERT(tcp->tcp_family == AF_INET6);
26166 		error = tcp->tcp_ipversion == IPV6_VERSION ?
26167 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26168 		if (error) {
26169 			return (ENOMEM);
26170 		}
26171 	}
26172 
26173 	/*
26174 	 * Initialize family specific fields. Copy of the src addr.
26175 	 * in tcp_t is needed for the lookup funcs.
26176 	 */
26177 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26178 		tcp->tcp_ip6h->ip6_src = v6addr;
26179 	} else {
26180 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
26181 	}
26182 	tcp->tcp_ip_src_v6 = v6addr;
26183 
26184 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
26185 
26186 	error = tcp_bind_select_lport(tcp, &requested_port,
26187 	    bind_to_req_port_only, cr);
26188 
26189 	return (error);
26190 }
26191 
26192 /*
26193  * Return unix error is tli error is TSYSERR, otherwise return a negative
26194  * tli error.
26195  */
26196 int
26197 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26198     boolean_t bind_to_req_port_only)
26199 {
26200 	int error;
26201 	tcp_t *tcp = connp->conn_tcp;
26202 
26203 	if (tcp->tcp_state >= TCPS_BOUND) {
26204 		if (tcp->tcp_debug) {
26205 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26206 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26207 		}
26208 		return (-TOUTSTATE);
26209 	}
26210 
26211 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
26212 	if (error != 0)
26213 		return (error);
26214 
26215 	ASSERT(tcp->tcp_state == TCPS_BOUND);
26216 
26217 	tcp->tcp_conn_req_max = 0;
26218 
26219 	if (tcp->tcp_family == AF_INET6) {
26220 		ASSERT(tcp->tcp_connp->conn_af_isv6);
26221 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
26222 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
26223 	} else {
26224 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
26225 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
26226 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
26227 	}
26228 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
26229 }
26230 
26231 int
26232 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
26233     socklen_t len, cred_t *cr)
26234 {
26235 	int 		error;
26236 	conn_t		*connp = (conn_t *)proto_handle;
26237 	squeue_t	*sqp = connp->conn_sqp;
26238 
26239 	/* All Solaris components should pass a cred for this operation. */
26240 	ASSERT(cr != NULL);
26241 
26242 	ASSERT(sqp != NULL);
26243 	ASSERT(connp->conn_upper_handle != NULL);
26244 
26245 	error = squeue_synch_enter(sqp, connp, NULL);
26246 	if (error != 0) {
26247 		/* failed to enter */
26248 		return (ENOSR);
26249 	}
26250 
26251 	/* binding to a NULL address really means unbind */
26252 	if (sa == NULL) {
26253 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
26254 			error = tcp_do_unbind(connp);
26255 		else
26256 			error = EINVAL;
26257 	} else {
26258 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
26259 	}
26260 
26261 	squeue_synch_exit(sqp, connp);
26262 
26263 	if (error < 0) {
26264 		if (error == -TOUTSTATE)
26265 			error = EINVAL;
26266 		else
26267 			error = proto_tlitosyserr(-error);
26268 	}
26269 
26270 	return (error);
26271 }
26272 
26273 /*
26274  * If the return value from this function is positive, it's a UNIX error.
26275  * Otherwise, if it's negative, then the absolute value is a TLI error.
26276  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
26277  */
26278 int
26279 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
26280     cred_t *cr, pid_t pid)
26281 {
26282 	tcp_t		*tcp = connp->conn_tcp;
26283 	sin_t		*sin = (sin_t *)sa;
26284 	sin6_t		*sin6 = (sin6_t *)sa;
26285 	ipaddr_t	*dstaddrp;
26286 	in_port_t	dstport;
26287 	uint_t		srcid;
26288 	int		error = 0;
26289 
26290 	switch (len) {
26291 	default:
26292 		/*
26293 		 * Should never happen
26294 		 */
26295 		return (EINVAL);
26296 
26297 	case sizeof (sin_t):
26298 		sin = (sin_t *)sa;
26299 		if (sin->sin_port == 0) {
26300 			return (-TBADADDR);
26301 		}
26302 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
26303 			return (EAFNOSUPPORT);
26304 		}
26305 		break;
26306 
26307 	case sizeof (sin6_t):
26308 		sin6 = (sin6_t *)sa;
26309 		if (sin6->sin6_port == 0) {
26310 			return (-TBADADDR);
26311 		}
26312 		break;
26313 	}
26314 	/*
26315 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
26316 	 * make sure that the template IP header in the tcp structure is an
26317 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
26318 	 * need to this before we call tcp_bindi() so that the port lookup
26319 	 * code will look for ports in the correct port space (IPv4 and
26320 	 * IPv6 have separate port spaces).
26321 	 */
26322 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
26323 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26324 		int err = 0;
26325 
26326 		err = tcp_header_init_ipv4(tcp);
26327 			if (err != 0) {
26328 				error = ENOMEM;
26329 				goto connect_failed;
26330 			}
26331 		if (tcp->tcp_lport != 0)
26332 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
26333 	}
26334 
26335 	switch (tcp->tcp_state) {
26336 	case TCPS_LISTEN:
26337 		/*
26338 		 * Listening sockets are not allowed to issue connect().
26339 		 */
26340 		if (IPCL_IS_NONSTR(connp))
26341 			return (EOPNOTSUPP);
26342 		/* FALLTHRU */
26343 	case TCPS_IDLE:
26344 		/*
26345 		 * We support quick connect, refer to comments in
26346 		 * tcp_connect_*()
26347 		 */
26348 		/* FALLTHRU */
26349 	case TCPS_BOUND:
26350 		/*
26351 		 * We must bump the generation before the operation start.
26352 		 * This is done to ensure that any upcall made later on sends
26353 		 * up the right generation to the socket.
26354 		 */
26355 		SOCK_CONNID_BUMP(tcp->tcp_connid);
26356 
26357 		if (tcp->tcp_family == AF_INET6) {
26358 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26359 				return (tcp_connect_ipv6(tcp,
26360 				    &sin6->sin6_addr,
26361 				    sin6->sin6_port, sin6->sin6_flowinfo,
26362 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
26363 				    cr, pid));
26364 			}
26365 			/*
26366 			 * Destination adress is mapped IPv6 address.
26367 			 * Source bound address should be unspecified or
26368 			 * IPv6 mapped address as well.
26369 			 */
26370 			if (!IN6_IS_ADDR_UNSPECIFIED(
26371 			    &tcp->tcp_bound_source_v6) &&
26372 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
26373 				return (EADDRNOTAVAIL);
26374 			}
26375 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
26376 			dstport = sin6->sin6_port;
26377 			srcid = sin6->__sin6_src_id;
26378 		} else {
26379 			dstaddrp = &sin->sin_addr.s_addr;
26380 			dstport = sin->sin_port;
26381 			srcid = 0;
26382 		}
26383 
26384 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
26385 		    pid);
26386 		break;
26387 	default:
26388 		return (-TOUTSTATE);
26389 	}
26390 	/*
26391 	 * Note: Code below is the "failure" case
26392 	 */
26393 connect_failed:
26394 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26395 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26396 	return (error);
26397 }
26398 
26399 int
26400 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
26401     socklen_t len, sock_connid_t *id, cred_t *cr)
26402 {
26403 	conn_t		*connp = (conn_t *)proto_handle;
26404 	tcp_t		*tcp = connp->conn_tcp;
26405 	squeue_t	*sqp = connp->conn_sqp;
26406 	int		error;
26407 
26408 	ASSERT(connp->conn_upper_handle != NULL);
26409 
26410 	/* All Solaris components should pass a cred for this operation. */
26411 	ASSERT(cr != NULL);
26412 
26413 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
26414 	if (error != 0) {
26415 		return (error);
26416 	}
26417 
26418 	error = squeue_synch_enter(sqp, connp, NULL);
26419 	if (error != 0) {
26420 		/* failed to enter */
26421 		return (ENOSR);
26422 	}
26423 
26424 	/*
26425 	 * TCP supports quick connect, so no need to do an implicit bind
26426 	 */
26427 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
26428 	if (error == 0) {
26429 		*id = connp->conn_tcp->tcp_connid;
26430 	} else if (error < 0) {
26431 		if (error == -TOUTSTATE) {
26432 			switch (connp->conn_tcp->tcp_state) {
26433 			case TCPS_SYN_SENT:
26434 				error = EALREADY;
26435 				break;
26436 			case TCPS_ESTABLISHED:
26437 				error = EISCONN;
26438 				break;
26439 			case TCPS_LISTEN:
26440 				error = EOPNOTSUPP;
26441 				break;
26442 			default:
26443 				error = EINVAL;
26444 				break;
26445 			}
26446 		} else {
26447 			error = proto_tlitosyserr(-error);
26448 		}
26449 	}
26450 
26451 	if (tcp->tcp_loopback) {
26452 		struct sock_proto_props sopp;
26453 
26454 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
26455 		sopp.sopp_loopback = B_TRUE;
26456 
26457 		(*connp->conn_upcalls->su_set_proto_props)(
26458 		    connp->conn_upper_handle, &sopp);
26459 	}
26460 done:
26461 	squeue_synch_exit(sqp, connp);
26462 
26463 	return ((error == 0) ? EINPROGRESS : error);
26464 }
26465 
26466 /* ARGSUSED */
26467 sock_lower_handle_t
26468 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
26469     uint_t *smodep, int *errorp, int flags, cred_t *credp)
26470 {
26471 	conn_t		*connp;
26472 	boolean_t	isv6 = family == AF_INET6;
26473 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
26474 	    (proto != 0 && proto != IPPROTO_TCP)) {
26475 		*errorp = EPROTONOSUPPORT;
26476 		return (NULL);
26477 	}
26478 
26479 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
26480 	if (connp == NULL) {
26481 		return (NULL);
26482 	}
26483 
26484 	/*
26485 	 * Put the ref for TCP. Ref for IP was already put
26486 	 * by ipcl_conn_create. Also Make the conn_t globally
26487 	 * visible to walkers
26488 	 */
26489 	mutex_enter(&connp->conn_lock);
26490 	CONN_INC_REF_LOCKED(connp);
26491 	ASSERT(connp->conn_ref == 2);
26492 	connp->conn_state_flags &= ~CONN_INCIPIENT;
26493 
26494 	connp->conn_flags |= IPCL_NONSTR;
26495 	mutex_exit(&connp->conn_lock);
26496 
26497 	ASSERT(errorp != NULL);
26498 	*errorp = 0;
26499 	*sock_downcalls = &sock_tcp_downcalls;
26500 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
26501 	    SM_SENDFILESUPP;
26502 
26503 	return ((sock_lower_handle_t)connp);
26504 }
26505 
26506 /* ARGSUSED */
26507 void
26508 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
26509     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
26510 {
26511 	conn_t *connp = (conn_t *)proto_handle;
26512 	struct sock_proto_props sopp;
26513 
26514 	ASSERT(connp->conn_upper_handle == NULL);
26515 
26516 	/* All Solaris components should pass a cred for this operation. */
26517 	ASSERT(cr != NULL);
26518 
26519 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
26520 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
26521 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
26522 
26523 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
26524 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
26525 	sopp.sopp_maxpsz = INFPSZ;
26526 	sopp.sopp_maxblk = INFPSZ;
26527 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
26528 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
26529 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
26530 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
26531 	    tcp_rinfo.mi_minpsz;
26532 
26533 	connp->conn_upcalls = sock_upcalls;
26534 	connp->conn_upper_handle = sock_handle;
26535 
26536 	ASSERT(connp->conn_tcp->tcp_recv_hiwater != 0 &&
26537 	    connp->conn_tcp->tcp_recv_hiwater == connp->conn_tcp->tcp_rwnd);
26538 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
26539 }
26540 
26541 /* ARGSUSED */
26542 int
26543 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
26544 {
26545 	conn_t *connp = (conn_t *)proto_handle;
26546 
26547 	ASSERT(connp->conn_upper_handle != NULL);
26548 
26549 	/* All Solaris components should pass a cred for this operation. */
26550 	ASSERT(cr != NULL);
26551 
26552 	tcp_close_common(connp, flags);
26553 
26554 	ip_free_helper_stream(connp);
26555 
26556 	/*
26557 	 * Drop IP's reference on the conn. This is the last reference
26558 	 * on the connp if the state was less than established. If the
26559 	 * connection has gone into timewait state, then we will have
26560 	 * one ref for the TCP and one more ref (total of two) for the
26561 	 * classifier connected hash list (a timewait connections stays
26562 	 * in connected hash till closed).
26563 	 *
26564 	 * We can't assert the references because there might be other
26565 	 * transient reference places because of some walkers or queued
26566 	 * packets in squeue for the timewait state.
26567 	 */
26568 	CONN_DEC_REF(connp);
26569 	return (0);
26570 }
26571 
26572 /* ARGSUSED */
26573 int
26574 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
26575     cred_t *cr)
26576 {
26577 	tcp_t		*tcp;
26578 	uint32_t	msize;
26579 	conn_t *connp = (conn_t *)proto_handle;
26580 	int32_t		tcpstate;
26581 
26582 	/* All Solaris components should pass a cred for this operation. */
26583 	ASSERT(cr != NULL);
26584 
26585 	ASSERT(connp->conn_ref >= 2);
26586 	ASSERT(connp->conn_upper_handle != NULL);
26587 
26588 	if (msg->msg_controllen != 0) {
26589 		return (EOPNOTSUPP);
26590 
26591 	}
26592 	switch (DB_TYPE(mp)) {
26593 	case M_DATA:
26594 		tcp = connp->conn_tcp;
26595 		ASSERT(tcp != NULL);
26596 
26597 		tcpstate = tcp->tcp_state;
26598 		if (tcpstate < TCPS_ESTABLISHED) {
26599 			freemsg(mp);
26600 			return (ENOTCONN);
26601 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
26602 			freemsg(mp);
26603 			return (EPIPE);
26604 		}
26605 
26606 		msize = msgdsize(mp);
26607 
26608 		mutex_enter(&tcp->tcp_non_sq_lock);
26609 		tcp->tcp_squeue_bytes += msize;
26610 		/*
26611 		 * Squeue Flow Control
26612 		 */
26613 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
26614 			tcp_setqfull(tcp);
26615 		}
26616 		mutex_exit(&tcp->tcp_non_sq_lock);
26617 
26618 		/*
26619 		 * The application may pass in an address in the msghdr, but
26620 		 * we ignore the address on connection-oriented sockets.
26621 		 * Just like BSD this code does not generate an error for
26622 		 * TCP (a CONNREQUIRED socket) when sending to an address
26623 		 * passed in with sendto/sendmsg. Instead the data is
26624 		 * delivered on the connection as if no address had been
26625 		 * supplied.
26626 		 */
26627 		CONN_INC_REF(connp);
26628 
26629 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
26630 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
26631 			    tcp_output_urgent, connp, tcp_squeue_flag,
26632 			    SQTAG_TCP_OUTPUT);
26633 		} else {
26634 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
26635 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
26636 		}
26637 
26638 		return (0);
26639 
26640 	default:
26641 		ASSERT(0);
26642 	}
26643 
26644 	freemsg(mp);
26645 	return (0);
26646 }
26647 
26648 /* ARGSUSED */
26649 void
26650 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
26651 {
26652 	int len;
26653 	uint32_t msize;
26654 	conn_t *connp = (conn_t *)arg;
26655 	tcp_t *tcp = connp->conn_tcp;
26656 
26657 	msize = msgdsize(mp);
26658 
26659 	len = msize - 1;
26660 	if (len < 0) {
26661 		freemsg(mp);
26662 		return;
26663 	}
26664 
26665 	/*
26666 	 * Try to force urgent data out on the wire. Even if we have unsent
26667 	 * data this will at least send the urgent flag.
26668 	 * XXX does not handle more flag correctly.
26669 	 */
26670 	len += tcp->tcp_unsent;
26671 	len += tcp->tcp_snxt;
26672 	tcp->tcp_urg = len;
26673 	tcp->tcp_valid_bits |= TCP_URG_VALID;
26674 
26675 	/* Bypass tcp protocol for fused tcp loopback */
26676 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
26677 		return;
26678 
26679 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
26680 	if (DB_TYPE(mp) != M_DATA) {
26681 		mblk_t *mp1 = mp;
26682 		ASSERT(!IPCL_IS_NONSTR(connp));
26683 		mp = mp->b_cont;
26684 		freeb(mp1);
26685 	}
26686 	tcp_wput_data(tcp, mp, B_TRUE);
26687 }
26688 
26689 /* ARGSUSED */
26690 int
26691 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26692     socklen_t *addrlenp, cred_t *cr)
26693 {
26694 	conn_t	*connp = (conn_t *)proto_handle;
26695 	tcp_t	*tcp = connp->conn_tcp;
26696 
26697 	ASSERT(connp->conn_upper_handle != NULL);
26698 	/* All Solaris components should pass a cred for this operation. */
26699 	ASSERT(cr != NULL);
26700 
26701 	ASSERT(tcp != NULL);
26702 
26703 	return (tcp_do_getpeername(tcp, addr, addrlenp));
26704 }
26705 
26706 /* ARGSUSED */
26707 int
26708 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26709     socklen_t *addrlenp, cred_t *cr)
26710 {
26711 	conn_t	*connp = (conn_t *)proto_handle;
26712 	tcp_t	*tcp = connp->conn_tcp;
26713 
26714 	/* All Solaris components should pass a cred for this operation. */
26715 	ASSERT(cr != NULL);
26716 
26717 	ASSERT(connp->conn_upper_handle != NULL);
26718 
26719 	return (tcp_do_getsockname(tcp, addr, addrlenp));
26720 }
26721 
26722 /*
26723  * tcp_fallback
26724  *
26725  * A direct socket is falling back to using STREAMS. The queue
26726  * that is being passed down was created using tcp_open() with
26727  * the SO_FALLBACK flag set. As a result, the queue is not
26728  * associated with a conn, and the q_ptrs instead contain the
26729  * dev and minor area that should be used.
26730  *
26731  * The 'issocket' flag indicates whether the FireEngine
26732  * optimizations should be used. The common case would be that
26733  * optimizations are enabled, and they might be subsequently
26734  * disabled using the _SIOCSOCKFALLBACK ioctl.
26735  */
26736 
26737 /*
26738  * An active connection is falling back to TPI. Gather all the information
26739  * required by the STREAM head and TPI sonode and send it up.
26740  */
26741 void
26742 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
26743     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
26744 {
26745 	conn_t			*connp = tcp->tcp_connp;
26746 	struct stroptions	*stropt;
26747 	struct T_capability_ack tca;
26748 	struct sockaddr_in6	laddr, faddr;
26749 	socklen_t 		laddrlen, faddrlen;
26750 	short			opts;
26751 	int			error;
26752 	mblk_t			*mp;
26753 
26754 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
26755 	connp->conn_minor_arena = WR(q)->q_ptr;
26756 
26757 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
26758 
26759 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
26760 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
26761 
26762 	WR(q)->q_qinfo = &tcp_sock_winit;
26763 
26764 	if (!issocket)
26765 		tcp_use_pure_tpi(tcp);
26766 
26767 	/*
26768 	 * free the helper stream
26769 	 */
26770 	ip_free_helper_stream(connp);
26771 
26772 	/*
26773 	 * Notify the STREAM head about options
26774 	 */
26775 	DB_TYPE(stropt_mp) = M_SETOPTS;
26776 	stropt = (struct stroptions *)stropt_mp->b_rptr;
26777 	stropt_mp->b_wptr += sizeof (struct stroptions);
26778 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
26779 
26780 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
26781 	    tcp->tcp_tcps->tcps_wroff_xtra);
26782 	if (tcp->tcp_snd_sack_ok)
26783 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
26784 	stropt->so_hiwat = tcp->tcp_recv_hiwater;
26785 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
26786 
26787 	putnext(RD(q), stropt_mp);
26788 
26789 	/*
26790 	 * Collect the information needed to sync with the sonode
26791 	 */
26792 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
26793 
26794 	laddrlen = faddrlen = sizeof (sin6_t);
26795 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
26796 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
26797 	if (error != 0)
26798 		faddrlen = 0;
26799 
26800 	opts = 0;
26801 	if (tcp->tcp_oobinline)
26802 		opts |= SO_OOBINLINE;
26803 	if (tcp->tcp_dontroute)
26804 		opts |= SO_DONTROUTE;
26805 
26806 	/*
26807 	 * Notify the socket that the protocol is now quiescent,
26808 	 * and it's therefore safe move data from the socket
26809 	 * to the stream head.
26810 	 */
26811 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
26812 	    (struct sockaddr *)&laddr, laddrlen,
26813 	    (struct sockaddr *)&faddr, faddrlen, opts);
26814 
26815 	while ((mp = tcp->tcp_rcv_list) != NULL) {
26816 		tcp->tcp_rcv_list = mp->b_next;
26817 		mp->b_next = NULL;
26818 		putnext(q, mp);
26819 	}
26820 	tcp->tcp_rcv_last_head = NULL;
26821 	tcp->tcp_rcv_last_tail = NULL;
26822 	tcp->tcp_rcv_cnt = 0;
26823 }
26824 
26825 /*
26826  * An eager is falling back to TPI. All we have to do is send
26827  * up a T_CONN_IND.
26828  */
26829 void
26830 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
26831 {
26832 	tcp_t *listener = eager->tcp_listener;
26833 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
26834 
26835 	ASSERT(listener != NULL);
26836 	ASSERT(mp != NULL);
26837 
26838 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
26839 
26840 	/*
26841 	 * TLI/XTI applications will get confused by
26842 	 * sending eager as an option since it violates
26843 	 * the option semantics. So remove the eager as
26844 	 * option since TLI/XTI app doesn't need it anyway.
26845 	 */
26846 	if (!direct_sockfs) {
26847 		struct T_conn_ind *conn_ind;
26848 
26849 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
26850 		conn_ind->OPT_length = 0;
26851 		conn_ind->OPT_offset = 0;
26852 	}
26853 
26854 	/*
26855 	 * Sockfs guarantees that the listener will not be closed
26856 	 * during fallback. So we can safely use the listener's queue.
26857 	 */
26858 	putnext(listener->tcp_rq, mp);
26859 }
26860 
26861 int
26862 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
26863     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
26864 {
26865 	tcp_t			*tcp;
26866 	conn_t 			*connp = (conn_t *)proto_handle;
26867 	int			error;
26868 	mblk_t			*stropt_mp;
26869 	mblk_t			*ordrel_mp;
26870 
26871 	tcp = connp->conn_tcp;
26872 
26873 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
26874 	    NULL);
26875 
26876 	/* Pre-allocate the T_ordrel_ind mblk. */
26877 	ASSERT(tcp->tcp_ordrel_mp == NULL);
26878 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
26879 	    STR_NOSIG, NULL);
26880 	ordrel_mp->b_datap->db_type = M_PROTO;
26881 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
26882 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
26883 
26884 	/*
26885 	 * Enter the squeue so that no new packets can come in
26886 	 */
26887 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
26888 	if (error != 0) {
26889 		/* failed to enter, free all the pre-allocated messages. */
26890 		freeb(stropt_mp);
26891 		freeb(ordrel_mp);
26892 		/*
26893 		 * We cannot process the eager, so at least send out a
26894 		 * RST so the peer can reconnect.
26895 		 */
26896 		if (tcp->tcp_listener != NULL) {
26897 			(void) tcp_eager_blowoff(tcp->tcp_listener,
26898 			    tcp->tcp_conn_req_seqnum);
26899 		}
26900 		return (ENOMEM);
26901 	}
26902 
26903 	/*
26904 	 * Both endpoints must be of the same type (either STREAMS or
26905 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
26906 	 * we have to unfuse.
26907 	 */
26908 	if (tcp->tcp_fused)
26909 		tcp_unfuse(tcp);
26910 
26911 	/*
26912 	 * No longer a direct socket
26913 	 */
26914 	connp->conn_flags &= ~IPCL_NONSTR;
26915 	tcp->tcp_ordrel_mp = ordrel_mp;
26916 
26917 	if (tcp->tcp_listener != NULL) {
26918 		/* The eager will deal with opts when accept() is called */
26919 		freeb(stropt_mp);
26920 		tcp_fallback_eager(tcp, direct_sockfs);
26921 	} else {
26922 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
26923 		    quiesced_cb);
26924 	}
26925 
26926 	/*
26927 	 * There should be atleast two ref's (IP + TCP)
26928 	 */
26929 	ASSERT(connp->conn_ref >= 2);
26930 	squeue_synch_exit(connp->conn_sqp, connp);
26931 
26932 	return (0);
26933 }
26934 
26935 /* ARGSUSED */
26936 static void
26937 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
26938 {
26939 	conn_t 	*connp = (conn_t *)arg;
26940 	tcp_t	*tcp = connp->conn_tcp;
26941 
26942 	freemsg(mp);
26943 
26944 	if (tcp->tcp_fused)
26945 		tcp_unfuse(tcp);
26946 
26947 	if (tcp_xmit_end(tcp) != 0) {
26948 		/*
26949 		 * We were crossing FINs and got a reset from
26950 		 * the other side. Just ignore it.
26951 		 */
26952 		if (tcp->tcp_debug) {
26953 			(void) strlog(TCP_MOD_ID, 0, 1,
26954 			    SL_ERROR|SL_TRACE,
26955 			    "tcp_shutdown_output() out of state %s",
26956 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
26957 		}
26958 	}
26959 }
26960 
26961 /* ARGSUSED */
26962 int
26963 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
26964 {
26965 	conn_t  *connp = (conn_t *)proto_handle;
26966 	tcp_t   *tcp = connp->conn_tcp;
26967 
26968 	ASSERT(connp->conn_upper_handle != NULL);
26969 
26970 	/* All Solaris components should pass a cred for this operation. */
26971 	ASSERT(cr != NULL);
26972 
26973 	/*
26974 	 * X/Open requires that we check the connected state.
26975 	 */
26976 	if (tcp->tcp_state < TCPS_SYN_SENT)
26977 		return (ENOTCONN);
26978 
26979 	/* shutdown the send side */
26980 	if (how != SHUT_RD) {
26981 		mblk_t *bp;
26982 
26983 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
26984 		CONN_INC_REF(connp);
26985 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
26986 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
26987 
26988 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
26989 		    SOCK_OPCTL_SHUT_SEND, 0);
26990 	}
26991 
26992 	/* shutdown the recv side */
26993 	if (how != SHUT_WR)
26994 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
26995 		    SOCK_OPCTL_SHUT_RECV, 0);
26996 
26997 	return (0);
26998 }
26999 
27000 /*
27001  * SOP_LISTEN() calls into tcp_listen().
27002  */
27003 /* ARGSUSED */
27004 int
27005 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27006 {
27007 	conn_t	*connp = (conn_t *)proto_handle;
27008 	int 	error;
27009 	squeue_t *sqp = connp->conn_sqp;
27010 
27011 	ASSERT(connp->conn_upper_handle != NULL);
27012 
27013 	/* All Solaris components should pass a cred for this operation. */
27014 	ASSERT(cr != NULL);
27015 
27016 	error = squeue_synch_enter(sqp, connp, NULL);
27017 	if (error != 0) {
27018 		/* failed to enter */
27019 		return (ENOBUFS);
27020 	}
27021 
27022 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
27023 	if (error == 0) {
27024 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27025 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27026 	} else if (error < 0) {
27027 		if (error == -TOUTSTATE)
27028 			error = EINVAL;
27029 		else
27030 			error = proto_tlitosyserr(-error);
27031 	}
27032 	squeue_synch_exit(sqp, connp);
27033 	return (error);
27034 }
27035 
27036 static int
27037 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
27038     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
27039 {
27040 	tcp_t		*tcp = connp->conn_tcp;
27041 	int		error = 0;
27042 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27043 
27044 	/* All Solaris components should pass a cred for this operation. */
27045 	ASSERT(cr != NULL);
27046 
27047 	if (tcp->tcp_state >= TCPS_BOUND) {
27048 		if ((tcp->tcp_state == TCPS_BOUND ||
27049 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27050 			/*
27051 			 * Handle listen() increasing backlog.
27052 			 * This is more "liberal" then what the TPI spec
27053 			 * requires but is needed to avoid a t_unbind
27054 			 * when handling listen() since the port number
27055 			 * might be "stolen" between the unbind and bind.
27056 			 */
27057 			goto do_listen;
27058 		}
27059 		if (tcp->tcp_debug) {
27060 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27061 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27062 		}
27063 		return (-TOUTSTATE);
27064 	} else {
27065 		if (sa == NULL) {
27066 			sin6_t	addr;
27067 			sin_t *sin;
27068 			sin6_t *sin6;
27069 
27070 			ASSERT(IPCL_IS_NONSTR(connp));
27071 
27072 			/* Do an implicit bind: Request for a generic port. */
27073 			if (tcp->tcp_family == AF_INET) {
27074 				len = sizeof (sin_t);
27075 				sin = (sin_t *)&addr;
27076 				*sin = sin_null;
27077 				sin->sin_family = AF_INET;
27078 				tcp->tcp_ipversion = IPV4_VERSION;
27079 			} else {
27080 				ASSERT(tcp->tcp_family == AF_INET6);
27081 				len = sizeof (sin6_t);
27082 				sin6 = (sin6_t *)&addr;
27083 				*sin6 = sin6_null;
27084 				sin6->sin6_family = AF_INET6;
27085 				tcp->tcp_ipversion = IPV6_VERSION;
27086 			}
27087 			sa = (struct sockaddr *)&addr;
27088 		}
27089 
27090 		error = tcp_bind_check(connp, sa, len, cr,
27091 		    bind_to_req_port_only);
27092 		if (error)
27093 			return (error);
27094 		/* Fall through and do the fanout insertion */
27095 	}
27096 
27097 do_listen:
27098 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27099 	tcp->tcp_conn_req_max = backlog;
27100 	if (tcp->tcp_conn_req_max) {
27101 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27102 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27103 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27104 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27105 		/*
27106 		 * If this is a listener, do not reset the eager list
27107 		 * and other stuffs.  Note that we don't check if the
27108 		 * existing eager list meets the new tcp_conn_req_max
27109 		 * requirement.
27110 		 */
27111 		if (tcp->tcp_state != TCPS_LISTEN) {
27112 			tcp->tcp_state = TCPS_LISTEN;
27113 			/* Initialize the chain. Don't need the eager_lock */
27114 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27115 			tcp->tcp_eager_next_drop_q0 = tcp;
27116 			tcp->tcp_eager_prev_drop_q0 = tcp;
27117 			tcp->tcp_second_ctimer_threshold =
27118 			    tcps->tcps_ip_abort_linterval;
27119 		}
27120 	}
27121 
27122 	/*
27123 	 * We can call ip_bind directly, the processing continues
27124 	 * in tcp_post_ip_bind().
27125 	 *
27126 	 * We need to make sure that the conn_recv is set to a non-null
27127 	 * value before we insert the conn into the classifier table.
27128 	 * This is to avoid a race with an incoming packet which does an
27129 	 * ipcl_classify().
27130 	 */
27131 	connp->conn_recv = tcp_conn_request;
27132 	if (tcp->tcp_family == AF_INET) {
27133 		error = ip_proto_bind_laddr_v4(connp, NULL,
27134 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27135 	} else {
27136 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27137 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27138 	}
27139 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27140 }
27141 
27142 void
27143 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27144 {
27145 	conn_t  *connp = (conn_t *)proto_handle;
27146 	tcp_t	*tcp = connp->conn_tcp;
27147 	mblk_t *mp;
27148 	int error;
27149 
27150 	ASSERT(connp->conn_upper_handle != NULL);
27151 
27152 	/*
27153 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
27154 	 * is currently running.
27155 	 */
27156 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27157 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
27158 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
27159 		return;
27160 	}
27161 	tcp->tcp_rsrv_mp = NULL;
27162 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27163 
27164 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
27165 	ASSERT(error == 0);
27166 
27167 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27168 	tcp->tcp_rsrv_mp = mp;
27169 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27170 
27171 	if (tcp->tcp_fused) {
27172 		tcp_fuse_backenable(tcp);
27173 	} else {
27174 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27175 		/*
27176 		 * Send back a window update immediately if TCP is above
27177 		 * ESTABLISHED state and the increase of the rcv window
27178 		 * that the other side knows is at least 1 MSS after flow
27179 		 * control is lifted.
27180 		 */
27181 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27182 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
27183 			tcp_xmit_ctl(NULL, tcp,
27184 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27185 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27186 		}
27187 	}
27188 
27189 	squeue_synch_exit(connp->conn_sqp, connp);
27190 }
27191 
27192 /* ARGSUSED */
27193 int
27194 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27195     int mode, int32_t *rvalp, cred_t *cr)
27196 {
27197 	conn_t  	*connp = (conn_t *)proto_handle;
27198 	int		error;
27199 
27200 	ASSERT(connp->conn_upper_handle != NULL);
27201 
27202 	/* All Solaris components should pass a cred for this operation. */
27203 	ASSERT(cr != NULL);
27204 
27205 	switch (cmd) {
27206 		case ND_SET:
27207 		case ND_GET:
27208 		case TCP_IOC_DEFAULT_Q:
27209 		case _SIOCSOCKFALLBACK:
27210 		case TCP_IOC_ABORT_CONN:
27211 		case TI_GETPEERNAME:
27212 		case TI_GETMYNAME:
27213 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27214 			    cmd));
27215 			error = EINVAL;
27216 			break;
27217 		default:
27218 			/*
27219 			 * Pass on to IP using helper stream
27220 			 */
27221 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
27222 			    cmd, arg, mode, cr, rvalp);
27223 			break;
27224 	}
27225 	return (error);
27226 }
27227 
27228 sock_downcalls_t sock_tcp_downcalls = {
27229 	tcp_activate,
27230 	tcp_accept,
27231 	tcp_bind,
27232 	tcp_listen,
27233 	tcp_connect,
27234 	tcp_getpeername,
27235 	tcp_getsockname,
27236 	tcp_getsockopt,
27237 	tcp_setsockopt,
27238 	tcp_sendmsg,
27239 	NULL,
27240 	NULL,
27241 	NULL,
27242 	tcp_shutdown,
27243 	tcp_clr_flowctrl,
27244 	tcp_ioctl,
27245 	tcp_close,
27246 };
27247