xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision f25619f6)
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_mss = tcps->tcps_mss_def_ipv6;
7838 	} else {
7839 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7840 	}
7841 	PRESERVE(tcp->tcp_ipversion);		/* Init in tcp_init_values */
7842 
7843 	tcp->tcp_bound_if = 0;
7844 	tcp->tcp_ipv6_recvancillary = 0;
7845 	tcp->tcp_recvifindex = 0;
7846 	tcp->tcp_recvhops = 0;
7847 	tcp->tcp_closed = 0;
7848 	tcp->tcp_cleandeathtag = 0;
7849 	if (tcp->tcp_hopopts != NULL) {
7850 		mi_free(tcp->tcp_hopopts);
7851 		tcp->tcp_hopopts = NULL;
7852 		tcp->tcp_hopoptslen = 0;
7853 	}
7854 	ASSERT(tcp->tcp_hopoptslen == 0);
7855 	if (tcp->tcp_dstopts != NULL) {
7856 		mi_free(tcp->tcp_dstopts);
7857 		tcp->tcp_dstopts = NULL;
7858 		tcp->tcp_dstoptslen = 0;
7859 	}
7860 	ASSERT(tcp->tcp_dstoptslen == 0);
7861 	if (tcp->tcp_rtdstopts != NULL) {
7862 		mi_free(tcp->tcp_rtdstopts);
7863 		tcp->tcp_rtdstopts = NULL;
7864 		tcp->tcp_rtdstoptslen = 0;
7865 	}
7866 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7867 	if (tcp->tcp_rthdr != NULL) {
7868 		mi_free(tcp->tcp_rthdr);
7869 		tcp->tcp_rthdr = NULL;
7870 		tcp->tcp_rthdrlen = 0;
7871 	}
7872 	ASSERT(tcp->tcp_rthdrlen == 0);
7873 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7874 
7875 	/* Reset fusion-related fields */
7876 	tcp->tcp_fused = B_FALSE;
7877 	tcp->tcp_unfusable = B_FALSE;
7878 	tcp->tcp_fused_sigurg = B_FALSE;
7879 	tcp->tcp_loopback_peer = NULL;
7880 
7881 	tcp->tcp_lso = B_FALSE;
7882 
7883 	tcp->tcp_in_ack_unsent = 0;
7884 	tcp->tcp_cork = B_FALSE;
7885 	tcp->tcp_tconnind_started = B_FALSE;
7886 
7887 	PRESERVE(tcp->tcp_squeue_bytes);
7888 
7889 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7890 	ASSERT(!tcp->tcp_kssl_pending);
7891 	PRESERVE(tcp->tcp_kssl_ent);
7892 
7893 	tcp->tcp_closemp_used = B_FALSE;
7894 
7895 	PRESERVE(tcp->tcp_rsrv_mp);
7896 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7897 
7898 #ifdef DEBUG
7899 	DONTCARE(tcp->tcmp_stk[0]);
7900 #endif
7901 
7902 	PRESERVE(tcp->tcp_connid);
7903 
7904 
7905 #undef	DONTCARE
7906 #undef	PRESERVE
7907 }
7908 
7909 /*
7910  * Allocate necessary resources and initialize state vector.
7911  * Guaranteed not to fail so that when an error is returned,
7912  * the caller doesn't need to do any additional cleanup.
7913  */
7914 int
7915 tcp_init(tcp_t *tcp, queue_t *q)
7916 {
7917 	int	err;
7918 
7919 	tcp->tcp_rq = q;
7920 	tcp->tcp_wq = WR(q);
7921 	tcp->tcp_state = TCPS_IDLE;
7922 	if ((err = tcp_init_values(tcp)) != 0)
7923 		tcp_timers_stop(tcp);
7924 	return (err);
7925 }
7926 
7927 static int
7928 tcp_init_values(tcp_t *tcp)
7929 {
7930 	int	err;
7931 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7932 
7933 	ASSERT((tcp->tcp_family == AF_INET &&
7934 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7935 	    (tcp->tcp_family == AF_INET6 &&
7936 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7937 	    tcp->tcp_ipversion == IPV6_VERSION)));
7938 
7939 	/*
7940 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7941 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7942 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7943 	 * during first few transmissions of a connection as seen in slow
7944 	 * links.
7945 	 */
7946 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7947 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7948 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7949 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7950 	    tcps->tcps_conn_grace_period;
7951 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7952 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7953 	tcp->tcp_timer_backoff = 0;
7954 	tcp->tcp_ms_we_have_waited = 0;
7955 	tcp->tcp_last_recv_time = lbolt;
7956 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7957 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7958 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7959 
7960 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7961 
7962 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7963 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7964 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7965 	/*
7966 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7967 	 * passive open.
7968 	 */
7969 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7970 
7971 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7972 
7973 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7974 
7975 	tcp->tcp_mdt_hdr_head = 0;
7976 	tcp->tcp_mdt_hdr_tail = 0;
7977 
7978 	/* Reset fusion-related fields */
7979 	tcp->tcp_fused = B_FALSE;
7980 	tcp->tcp_unfusable = B_FALSE;
7981 	tcp->tcp_fused_sigurg = B_FALSE;
7982 	tcp->tcp_loopback_peer = NULL;
7983 
7984 	/* Initialize the header template */
7985 	if (tcp->tcp_family == AF_INET) {
7986 		err = tcp_header_init_ipv4(tcp);
7987 	} else {
7988 		err = tcp_header_init_ipv6(tcp);
7989 	}
7990 	if (err)
7991 		return (err);
7992 
7993 	/*
7994 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7995 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7996 	 */
7997 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7998 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7999 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8000 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
8001 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
8002 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
8003 
8004 	tcp->tcp_cork = B_FALSE;
8005 	/*
8006 	 * Init the tcp_debug option.  This value determines whether TCP
8007 	 * calls strlog() to print out debug messages.  Doing this
8008 	 * initialization here means that this value is not inherited thru
8009 	 * tcp_reinit().
8010 	 */
8011 	tcp->tcp_debug = tcps->tcps_dbg;
8012 
8013 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8014 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8015 
8016 	return (0);
8017 }
8018 
8019 /*
8020  * Initialize the IPv4 header. Loses any record of any IP options.
8021  */
8022 static int
8023 tcp_header_init_ipv4(tcp_t *tcp)
8024 {
8025 	tcph_t		*tcph;
8026 	uint32_t	sum;
8027 	conn_t		*connp;
8028 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8029 
8030 	/*
8031 	 * This is a simple initialization. If there's
8032 	 * already a template, it should never be too small,
8033 	 * so reuse it.  Otherwise, allocate space for the new one.
8034 	 */
8035 	if (tcp->tcp_iphc == NULL) {
8036 		ASSERT(tcp->tcp_iphc_len == 0);
8037 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8038 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8039 		if (tcp->tcp_iphc == NULL) {
8040 			tcp->tcp_iphc_len = 0;
8041 			return (ENOMEM);
8042 		}
8043 	}
8044 
8045 	/* options are gone; may need a new label */
8046 	connp = tcp->tcp_connp;
8047 	connp->conn_mlp_type = mlptSingle;
8048 	connp->conn_ulp_labeled = !is_system_labeled();
8049 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8050 
8051 	/*
8052 	 * tcp_do_get{sock,peer}name constructs the sockaddr from the
8053 	 * ip header, and decides which header to use based on ip version.
8054 	 * That operation happens outside the squeue, so we hold the lock
8055 	 * here to ensure that the ip version and header remain consistent.
8056 	 */
8057 	mutex_enter(&connp->conn_lock);
8058 	tcp->tcp_ipversion = IPV4_VERSION;
8059 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8060 	tcp->tcp_ip6h = NULL;
8061 	mutex_exit(&connp->conn_lock);
8062 
8063 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8064 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8065 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8066 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8067 	tcp->tcp_ipha->ipha_version_and_hdr_length
8068 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8069 	tcp->tcp_ipha->ipha_ident = 0;
8070 
8071 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8072 	tcp->tcp_tos = 0;
8073 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8074 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8075 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8076 
8077 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8078 	tcp->tcp_tcph = tcph;
8079 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8080 	/*
8081 	 * IP wants our header length in the checksum field to
8082 	 * allow it to perform a single pseudo-header+checksum
8083 	 * calculation on behalf of TCP.
8084 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8085 	 */
8086 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8087 	sum = (sum >> 16) + (sum & 0xFFFF);
8088 	U16_TO_ABE16(sum, tcph->th_sum);
8089 	return (0);
8090 }
8091 
8092 /*
8093  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8094  */
8095 static int
8096 tcp_header_init_ipv6(tcp_t *tcp)
8097 {
8098 	tcph_t	*tcph;
8099 	uint32_t	sum;
8100 	conn_t	*connp;
8101 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8102 
8103 	/*
8104 	 * This is a simple initialization. If there's
8105 	 * already a template, it should never be too small,
8106 	 * so reuse it. Otherwise, allocate space for the new one.
8107 	 * Ensure that there is enough space to "downgrade" the tcp_t
8108 	 * to an IPv4 tcp_t. This requires having space for a full load
8109 	 * of IPv4 options, as well as a full load of TCP options
8110 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8111 	 * than a v6 header and a TCP header with a full load of TCP options
8112 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8113 	 * We want to avoid reallocation in the "downgraded" case when
8114 	 * processing outbound IPv4 options.
8115 	 */
8116 	if (tcp->tcp_iphc == NULL) {
8117 		ASSERT(tcp->tcp_iphc_len == 0);
8118 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8119 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8120 		if (tcp->tcp_iphc == NULL) {
8121 			tcp->tcp_iphc_len = 0;
8122 			return (ENOMEM);
8123 		}
8124 	}
8125 
8126 	/* options are gone; may need a new label */
8127 	connp = tcp->tcp_connp;
8128 	connp->conn_mlp_type = mlptSingle;
8129 	connp->conn_ulp_labeled = !is_system_labeled();
8130 
8131 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8132 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8133 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8134 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8135 
8136 	/*
8137 	 * tcp_do_get{sock,peer}name constructs the sockaddr from the
8138 	 * ip header, and decides which header to use based on ip version.
8139 	 * That operation happens outside the squeue, so we hold the lock
8140 	 * here to ensure that the ip version and header remain consistent.
8141 	 */
8142 	mutex_enter(&connp->conn_lock);
8143 	tcp->tcp_ipversion = IPV6_VERSION;
8144 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8145 	tcp->tcp_ipha = NULL;
8146 	mutex_exit(&connp->conn_lock);
8147 
8148 	/* Initialize the header template */
8149 
8150 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8151 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8152 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8153 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8154 
8155 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8156 	tcp->tcp_tcph = tcph;
8157 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8158 	/*
8159 	 * IP wants our header length in the checksum field to
8160 	 * allow it to perform a single psuedo-header+checksum
8161 	 * calculation on behalf of TCP.
8162 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8163 	 */
8164 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8165 	sum = (sum >> 16) + (sum & 0xFFFF);
8166 	U16_TO_ABE16(sum, tcph->th_sum);
8167 	return (0);
8168 }
8169 
8170 /* At minimum we need 8 bytes in the TCP header for the lookup */
8171 #define	ICMP_MIN_TCP_HDR	8
8172 
8173 /*
8174  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8175  * passed up by IP. The message is always received on the correct tcp_t.
8176  * Assumes that IP has pulled up everything up to and including the ICMP header.
8177  */
8178 void
8179 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8180 {
8181 	icmph_t *icmph;
8182 	ipha_t	*ipha;
8183 	int	iph_hdr_length;
8184 	tcph_t	*tcph;
8185 	boolean_t ipsec_mctl = B_FALSE;
8186 	boolean_t secure;
8187 	mblk_t *first_mp = mp;
8188 	int32_t new_mss;
8189 	uint32_t ratio;
8190 	size_t mp_size = MBLKL(mp);
8191 	uint32_t seg_seq;
8192 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8193 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8194 
8195 	/* Assume IP provides aligned packets - otherwise toss */
8196 	if (!OK_32PTR(mp->b_rptr)) {
8197 		freemsg(mp);
8198 		return;
8199 	}
8200 
8201 	/*
8202 	 * Since ICMP errors are normal data marked with M_CTL when sent
8203 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8204 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8205 	 */
8206 	if ((mp_size == sizeof (ipsec_info_t)) &&
8207 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8208 		ASSERT(mp->b_cont != NULL);
8209 		mp = mp->b_cont;
8210 		/* IP should have done this */
8211 		ASSERT(OK_32PTR(mp->b_rptr));
8212 		mp_size = MBLKL(mp);
8213 		ipsec_mctl = B_TRUE;
8214 	}
8215 
8216 	/*
8217 	 * Verify that we have a complete outer IP header. If not, drop it.
8218 	 */
8219 	if (mp_size < sizeof (ipha_t)) {
8220 noticmpv4:
8221 		freemsg(first_mp);
8222 		return;
8223 	}
8224 
8225 	ipha = (ipha_t *)mp->b_rptr;
8226 	/*
8227 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8228 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8229 	 */
8230 	switch (IPH_HDR_VERSION(ipha)) {
8231 	case IPV6_VERSION:
8232 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8233 		return;
8234 	case IPV4_VERSION:
8235 		break;
8236 	default:
8237 		goto noticmpv4;
8238 	}
8239 
8240 	/* Skip past the outer IP and ICMP headers */
8241 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8242 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8243 	/*
8244 	 * If we don't have the correct outer IP header length or if the ULP
8245 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8246 	 * send it upstream.
8247 	 */
8248 	if (iph_hdr_length < sizeof (ipha_t) ||
8249 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8250 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8251 		goto noticmpv4;
8252 	}
8253 	ipha = (ipha_t *)&icmph[1];
8254 
8255 	/* Skip past the inner IP and find the ULP header */
8256 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8257 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8258 	/*
8259 	 * If we don't have the correct inner IP header length or if the ULP
8260 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8261 	 * bytes of TCP header, drop it.
8262 	 */
8263 	if (iph_hdr_length < sizeof (ipha_t) ||
8264 	    ipha->ipha_protocol != IPPROTO_TCP ||
8265 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8266 		goto noticmpv4;
8267 	}
8268 
8269 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8270 		if (ipsec_mctl) {
8271 			secure = ipsec_in_is_secure(first_mp);
8272 		} else {
8273 			secure = B_FALSE;
8274 		}
8275 		if (secure) {
8276 			/*
8277 			 * If we are willing to accept this in clear
8278 			 * we don't have to verify policy.
8279 			 */
8280 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8281 				if (!tcp_check_policy(tcp, first_mp,
8282 				    ipha, NULL, secure, ipsec_mctl)) {
8283 					/*
8284 					 * tcp_check_policy called
8285 					 * ip_drop_packet() on failure.
8286 					 */
8287 					return;
8288 				}
8289 			}
8290 		}
8291 	} else if (ipsec_mctl) {
8292 		/*
8293 		 * This is a hard_bound connection. IP has already
8294 		 * verified policy. We don't have to do it again.
8295 		 */
8296 		freeb(first_mp);
8297 		first_mp = mp;
8298 		ipsec_mctl = B_FALSE;
8299 	}
8300 
8301 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8302 	/*
8303 	 * TCP SHOULD check that the TCP sequence number contained in
8304 	 * payload of the ICMP error message is within the range
8305 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8306 	 */
8307 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8308 		/*
8309 		 * The ICMP message is bogus, just drop it.  But if this is
8310 		 * an ICMP too big message, IP has already changed
8311 		 * the ire_max_frag to the bogus value.  We need to change
8312 		 * it back.
8313 		 */
8314 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8315 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8316 			conn_t *connp = tcp->tcp_connp;
8317 			ire_t *ire;
8318 			int flag;
8319 
8320 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8321 				flag = tcp->tcp_ipha->
8322 				    ipha_fragment_offset_and_flags;
8323 			} else {
8324 				flag = 0;
8325 			}
8326 			mutex_enter(&connp->conn_lock);
8327 			if ((ire = connp->conn_ire_cache) != NULL) {
8328 				mutex_enter(&ire->ire_lock);
8329 				mutex_exit(&connp->conn_lock);
8330 				ire->ire_max_frag = tcp->tcp_if_mtu;
8331 				ire->ire_frag_flag |= flag;
8332 				mutex_exit(&ire->ire_lock);
8333 			} else {
8334 				mutex_exit(&connp->conn_lock);
8335 			}
8336 		}
8337 		goto noticmpv4;
8338 	}
8339 
8340 	switch (icmph->icmph_type) {
8341 	case ICMP_DEST_UNREACHABLE:
8342 		switch (icmph->icmph_code) {
8343 		case ICMP_FRAGMENTATION_NEEDED:
8344 			/*
8345 			 * Reduce the MSS based on the new MTU.  This will
8346 			 * eliminate any fragmentation locally.
8347 			 * N.B.  There may well be some funny side-effects on
8348 			 * the local send policy and the remote receive policy.
8349 			 * Pending further research, we provide
8350 			 * tcp_ignore_path_mtu just in case this proves
8351 			 * disastrous somewhere.
8352 			 *
8353 			 * After updating the MSS, retransmit part of the
8354 			 * dropped segment using the new mss by calling
8355 			 * tcp_wput_data().  Need to adjust all those
8356 			 * params to make sure tcp_wput_data() work properly.
8357 			 */
8358 			if (tcps->tcps_ignore_path_mtu ||
8359 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8360 				break;
8361 
8362 			/*
8363 			 * Decrease the MSS by time stamp options
8364 			 * IP options and IPSEC options. tcp_hdr_len
8365 			 * includes time stamp option and IP option
8366 			 * length.  Note that new_mss may be negative
8367 			 * if tcp_ipsec_overhead is large and the
8368 			 * icmph_du_mtu is the minimum value, which is 68.
8369 			 */
8370 			new_mss = ntohs(icmph->icmph_du_mtu) -
8371 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8372 
8373 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8374 			    new_mss);
8375 
8376 			/*
8377 			 * Only update the MSS if the new one is
8378 			 * smaller than the previous one.  This is
8379 			 * to avoid problems when getting multiple
8380 			 * ICMP errors for the same MTU.
8381 			 */
8382 			if (new_mss >= tcp->tcp_mss)
8383 				break;
8384 
8385 			/*
8386 			 * Note that we are using the template header's DF
8387 			 * bit in the fast path sending.  So we need to compare
8388 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8389 			 * And stop doing IPv4 PMTUd if new_mss is less than
8390 			 * MAX(tcps_mss_min, ip_pmtu_min).
8391 			 */
8392 			if (new_mss < tcps->tcps_mss_min ||
8393 			    new_mss < ipst->ips_ip_pmtu_min) {
8394 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8395 				    0;
8396 			}
8397 
8398 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8399 			ASSERT(ratio >= 1);
8400 			tcp_mss_set(tcp, new_mss, B_TRUE);
8401 
8402 			/*
8403 			 * Make sure we have something to
8404 			 * send.
8405 			 */
8406 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8407 			    (tcp->tcp_xmit_head != NULL)) {
8408 				/*
8409 				 * Shrink tcp_cwnd in
8410 				 * proportion to the old MSS/new MSS.
8411 				 */
8412 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8413 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8414 				    (tcp->tcp_unsent == 0)) {
8415 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8416 				} else {
8417 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8418 				}
8419 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8420 				tcp->tcp_rexmit = B_TRUE;
8421 				tcp->tcp_dupack_cnt = 0;
8422 				tcp->tcp_snd_burst = TCP_CWND_SS;
8423 				tcp_ss_rexmit(tcp);
8424 			}
8425 			break;
8426 		case ICMP_PORT_UNREACHABLE:
8427 		case ICMP_PROTOCOL_UNREACHABLE:
8428 			switch (tcp->tcp_state) {
8429 			case TCPS_SYN_SENT:
8430 			case TCPS_SYN_RCVD:
8431 				/*
8432 				 * ICMP can snipe away incipient
8433 				 * TCP connections as long as
8434 				 * seq number is same as initial
8435 				 * send seq number.
8436 				 */
8437 				if (seg_seq == tcp->tcp_iss) {
8438 					(void) tcp_clean_death(tcp,
8439 					    ECONNREFUSED, 6);
8440 				}
8441 				break;
8442 			}
8443 			break;
8444 		case ICMP_HOST_UNREACHABLE:
8445 		case ICMP_NET_UNREACHABLE:
8446 			/* Record the error in case we finally time out. */
8447 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8448 				tcp->tcp_client_errno = EHOSTUNREACH;
8449 			else
8450 				tcp->tcp_client_errno = ENETUNREACH;
8451 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8452 				if (tcp->tcp_listener != NULL &&
8453 				    tcp->tcp_listener->tcp_syn_defense) {
8454 					/*
8455 					 * Ditch the half-open connection if we
8456 					 * suspect a SYN attack is under way.
8457 					 */
8458 					tcp_ip_ire_mark_advice(tcp);
8459 					(void) tcp_clean_death(tcp,
8460 					    tcp->tcp_client_errno, 7);
8461 				}
8462 			}
8463 			break;
8464 		default:
8465 			break;
8466 		}
8467 		break;
8468 	case ICMP_SOURCE_QUENCH: {
8469 		/*
8470 		 * use a global boolean to control
8471 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8472 		 * The default is false.
8473 		 */
8474 		if (tcp_icmp_source_quench) {
8475 			/*
8476 			 * Reduce the sending rate as if we got a
8477 			 * retransmit timeout
8478 			 */
8479 			uint32_t npkt;
8480 
8481 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8482 			    tcp->tcp_mss;
8483 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8484 			tcp->tcp_cwnd = tcp->tcp_mss;
8485 			tcp->tcp_cwnd_cnt = 0;
8486 		}
8487 		break;
8488 	}
8489 	}
8490 	freemsg(first_mp);
8491 }
8492 
8493 /*
8494  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8495  * error messages passed up by IP.
8496  * Assumes that IP has pulled up all the extension headers as well
8497  * as the ICMPv6 header.
8498  */
8499 static void
8500 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8501 {
8502 	icmp6_t *icmp6;
8503 	ip6_t	*ip6h;
8504 	uint16_t	iph_hdr_length;
8505 	tcpha_t	*tcpha;
8506 	uint8_t	*nexthdrp;
8507 	uint32_t new_mss;
8508 	uint32_t ratio;
8509 	boolean_t secure;
8510 	mblk_t *first_mp = mp;
8511 	size_t mp_size;
8512 	uint32_t seg_seq;
8513 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8514 
8515 	/*
8516 	 * The caller has determined if this is an IPSEC_IN packet and
8517 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8518 	 */
8519 	if (ipsec_mctl)
8520 		mp = mp->b_cont;
8521 
8522 	mp_size = MBLKL(mp);
8523 
8524 	/*
8525 	 * Verify that we have a complete IP header. If not, send it upstream.
8526 	 */
8527 	if (mp_size < sizeof (ip6_t)) {
8528 noticmpv6:
8529 		freemsg(first_mp);
8530 		return;
8531 	}
8532 
8533 	/*
8534 	 * Verify this is an ICMPV6 packet, else send it upstream.
8535 	 */
8536 	ip6h = (ip6_t *)mp->b_rptr;
8537 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8538 		iph_hdr_length = IPV6_HDR_LEN;
8539 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8540 	    &nexthdrp) ||
8541 	    *nexthdrp != IPPROTO_ICMPV6) {
8542 		goto noticmpv6;
8543 	}
8544 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8545 	ip6h = (ip6_t *)&icmp6[1];
8546 	/*
8547 	 * Verify if we have a complete ICMP and inner IP header.
8548 	 */
8549 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8550 		goto noticmpv6;
8551 
8552 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8553 		goto noticmpv6;
8554 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8555 	/*
8556 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8557 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8558 	 * packet.
8559 	 */
8560 	if ((*nexthdrp != IPPROTO_TCP) ||
8561 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8562 		goto noticmpv6;
8563 	}
8564 
8565 	/*
8566 	 * ICMP errors come on the right queue or come on
8567 	 * listener/global queue for detached connections and
8568 	 * get switched to the right queue. If it comes on the
8569 	 * right queue, policy check has already been done by IP
8570 	 * and thus free the first_mp without verifying the policy.
8571 	 * If it has come for a non-hard bound connection, we need
8572 	 * to verify policy as IP may not have done it.
8573 	 */
8574 	if (!tcp->tcp_hard_bound) {
8575 		if (ipsec_mctl) {
8576 			secure = ipsec_in_is_secure(first_mp);
8577 		} else {
8578 			secure = B_FALSE;
8579 		}
8580 		if (secure) {
8581 			/*
8582 			 * If we are willing to accept this in clear
8583 			 * we don't have to verify policy.
8584 			 */
8585 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8586 				if (!tcp_check_policy(tcp, first_mp,
8587 				    NULL, ip6h, secure, ipsec_mctl)) {
8588 					/*
8589 					 * tcp_check_policy called
8590 					 * ip_drop_packet() on failure.
8591 					 */
8592 					return;
8593 				}
8594 			}
8595 		}
8596 	} else if (ipsec_mctl) {
8597 		/*
8598 		 * This is a hard_bound connection. IP has already
8599 		 * verified policy. We don't have to do it again.
8600 		 */
8601 		freeb(first_mp);
8602 		first_mp = mp;
8603 		ipsec_mctl = B_FALSE;
8604 	}
8605 
8606 	seg_seq = ntohl(tcpha->tha_seq);
8607 	/*
8608 	 * TCP SHOULD check that the TCP sequence number contained in
8609 	 * payload of the ICMP error message is within the range
8610 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8611 	 */
8612 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8613 		/*
8614 		 * If the ICMP message is bogus, should we kill the
8615 		 * connection, or should we just drop the bogus ICMP
8616 		 * message? It would probably make more sense to just
8617 		 * drop the message so that if this one managed to get
8618 		 * in, the real connection should not suffer.
8619 		 */
8620 		goto noticmpv6;
8621 	}
8622 
8623 	switch (icmp6->icmp6_type) {
8624 	case ICMP6_PACKET_TOO_BIG:
8625 		/*
8626 		 * Reduce the MSS based on the new MTU.  This will
8627 		 * eliminate any fragmentation locally.
8628 		 * N.B.  There may well be some funny side-effects on
8629 		 * the local send policy and the remote receive policy.
8630 		 * Pending further research, we provide
8631 		 * tcp_ignore_path_mtu just in case this proves
8632 		 * disastrous somewhere.
8633 		 *
8634 		 * After updating the MSS, retransmit part of the
8635 		 * dropped segment using the new mss by calling
8636 		 * tcp_wput_data().  Need to adjust all those
8637 		 * params to make sure tcp_wput_data() work properly.
8638 		 */
8639 		if (tcps->tcps_ignore_path_mtu)
8640 			break;
8641 
8642 		/*
8643 		 * Decrease the MSS by time stamp options
8644 		 * IP options and IPSEC options. tcp_hdr_len
8645 		 * includes time stamp option and IP option
8646 		 * length.
8647 		 */
8648 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8649 		    tcp->tcp_ipsec_overhead;
8650 
8651 		/*
8652 		 * Only update the MSS if the new one is
8653 		 * smaller than the previous one.  This is
8654 		 * to avoid problems when getting multiple
8655 		 * ICMP errors for the same MTU.
8656 		 */
8657 		if (new_mss >= tcp->tcp_mss)
8658 			break;
8659 
8660 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8661 		ASSERT(ratio >= 1);
8662 		tcp_mss_set(tcp, new_mss, B_TRUE);
8663 
8664 		/*
8665 		 * Make sure we have something to
8666 		 * send.
8667 		 */
8668 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8669 		    (tcp->tcp_xmit_head != NULL)) {
8670 			/*
8671 			 * Shrink tcp_cwnd in
8672 			 * proportion to the old MSS/new MSS.
8673 			 */
8674 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8675 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8676 			    (tcp->tcp_unsent == 0)) {
8677 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8678 			} else {
8679 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8680 			}
8681 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8682 			tcp->tcp_rexmit = B_TRUE;
8683 			tcp->tcp_dupack_cnt = 0;
8684 			tcp->tcp_snd_burst = TCP_CWND_SS;
8685 			tcp_ss_rexmit(tcp);
8686 		}
8687 		break;
8688 
8689 	case ICMP6_DST_UNREACH:
8690 		switch (icmp6->icmp6_code) {
8691 		case ICMP6_DST_UNREACH_NOPORT:
8692 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8693 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8694 			    (seg_seq == tcp->tcp_iss)) {
8695 				(void) tcp_clean_death(tcp,
8696 				    ECONNREFUSED, 8);
8697 			}
8698 			break;
8699 
8700 		case ICMP6_DST_UNREACH_ADMIN:
8701 		case ICMP6_DST_UNREACH_NOROUTE:
8702 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8703 		case ICMP6_DST_UNREACH_ADDR:
8704 			/* Record the error in case we finally time out. */
8705 			tcp->tcp_client_errno = EHOSTUNREACH;
8706 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8707 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8708 			    (seg_seq == tcp->tcp_iss)) {
8709 				if (tcp->tcp_listener != NULL &&
8710 				    tcp->tcp_listener->tcp_syn_defense) {
8711 					/*
8712 					 * Ditch the half-open connection if we
8713 					 * suspect a SYN attack is under way.
8714 					 */
8715 					tcp_ip_ire_mark_advice(tcp);
8716 					(void) tcp_clean_death(tcp,
8717 					    tcp->tcp_client_errno, 9);
8718 				}
8719 			}
8720 
8721 
8722 			break;
8723 		default:
8724 			break;
8725 		}
8726 		break;
8727 
8728 	case ICMP6_PARAM_PROB:
8729 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8730 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8731 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8732 		    (uchar_t *)nexthdrp) {
8733 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8734 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8735 				(void) tcp_clean_death(tcp,
8736 				    ECONNREFUSED, 10);
8737 			}
8738 			break;
8739 		}
8740 		break;
8741 
8742 	case ICMP6_TIME_EXCEEDED:
8743 	default:
8744 		break;
8745 	}
8746 	freemsg(first_mp);
8747 }
8748 
8749 /*
8750  * Notify IP that we are having trouble with this connection.  IP should
8751  * blow the IRE away and start over.
8752  */
8753 static void
8754 tcp_ip_notify(tcp_t *tcp)
8755 {
8756 	struct iocblk	*iocp;
8757 	ipid_t	*ipid;
8758 	mblk_t	*mp;
8759 
8760 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8761 	if (tcp->tcp_ipversion == IPV6_VERSION)
8762 		return;
8763 
8764 	mp = mkiocb(IP_IOCTL);
8765 	if (mp == NULL)
8766 		return;
8767 
8768 	iocp = (struct iocblk *)mp->b_rptr;
8769 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8770 
8771 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8772 	if (!mp->b_cont) {
8773 		freeb(mp);
8774 		return;
8775 	}
8776 
8777 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8778 	mp->b_cont->b_wptr += iocp->ioc_count;
8779 	bzero(ipid, sizeof (*ipid));
8780 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8781 	ipid->ipid_ire_type = IRE_CACHE;
8782 	ipid->ipid_addr_offset = sizeof (ipid_t);
8783 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8784 	/*
8785 	 * Note: in the case of source routing we want to blow away the
8786 	 * route to the first source route hop.
8787 	 */
8788 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8789 	    sizeof (tcp->tcp_ipha->ipha_dst));
8790 
8791 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8792 }
8793 
8794 /* Unlink and return any mblk that looks like it contains an ire */
8795 static mblk_t *
8796 tcp_ire_mp(mblk_t **mpp)
8797 {
8798 	mblk_t 	*mp = *mpp;
8799 	mblk_t	*prev_mp = NULL;
8800 
8801 	for (;;) {
8802 		switch (DB_TYPE(mp)) {
8803 		case IRE_DB_TYPE:
8804 		case IRE_DB_REQ_TYPE:
8805 			if (mp == *mpp) {
8806 				*mpp = mp->b_cont;
8807 			} else {
8808 				prev_mp->b_cont = mp->b_cont;
8809 			}
8810 			mp->b_cont = NULL;
8811 			return (mp);
8812 		default:
8813 			break;
8814 		}
8815 		prev_mp = mp;
8816 		mp = mp->b_cont;
8817 		if (mp == NULL)
8818 			break;
8819 	}
8820 	return (mp);
8821 }
8822 
8823 /*
8824  * Timer callback routine for keepalive probe.  We do a fake resend of
8825  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8826  * check to see if we have heard anything from the other end for the last
8827  * RTO period.  If we have, set the timer to expire for another
8828  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8829  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8830  * the timeout if we have not heard from the other side.  If for more than
8831  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8832  * kill the connection unless the keepalive abort threshold is 0.  In
8833  * that case, we will probe "forever."
8834  */
8835 static void
8836 tcp_keepalive_killer(void *arg)
8837 {
8838 	mblk_t	*mp;
8839 	conn_t	*connp = (conn_t *)arg;
8840 	tcp_t  	*tcp = connp->conn_tcp;
8841 	int32_t	firetime;
8842 	int32_t	idletime;
8843 	int32_t	ka_intrvl;
8844 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8845 
8846 	tcp->tcp_ka_tid = 0;
8847 
8848 	if (tcp->tcp_fused)
8849 		return;
8850 
8851 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8852 	ka_intrvl = tcp->tcp_ka_interval;
8853 
8854 	/*
8855 	 * Keepalive probe should only be sent if the application has not
8856 	 * done a close on the connection.
8857 	 */
8858 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8859 		return;
8860 	}
8861 	/* Timer fired too early, restart it. */
8862 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8863 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8864 		    MSEC_TO_TICK(ka_intrvl));
8865 		return;
8866 	}
8867 
8868 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8869 	/*
8870 	 * If we have not heard from the other side for a long
8871 	 * time, kill the connection unless the keepalive abort
8872 	 * threshold is 0.  In that case, we will probe "forever."
8873 	 */
8874 	if (tcp->tcp_ka_abort_thres != 0 &&
8875 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8876 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8877 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8878 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8879 		return;
8880 	}
8881 
8882 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8883 	    idletime >= ka_intrvl) {
8884 		/* Fake resend of last ACKed byte. */
8885 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8886 
8887 		if (mp1 != NULL) {
8888 			*mp1->b_wptr++ = '\0';
8889 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8890 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8891 			freeb(mp1);
8892 			/*
8893 			 * if allocation failed, fall through to start the
8894 			 * timer back.
8895 			 */
8896 			if (mp != NULL) {
8897 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8898 				BUMP_MIB(&tcps->tcps_mib,
8899 				    tcpTimKeepaliveProbe);
8900 				if (tcp->tcp_ka_last_intrvl != 0) {
8901 					int max;
8902 					/*
8903 					 * We should probe again at least
8904 					 * in ka_intrvl, but not more than
8905 					 * tcp_rexmit_interval_max.
8906 					 */
8907 					max = tcps->tcps_rexmit_interval_max;
8908 					firetime = MIN(ka_intrvl - 1,
8909 					    tcp->tcp_ka_last_intrvl << 1);
8910 					if (firetime > max)
8911 						firetime = max;
8912 				} else {
8913 					firetime = tcp->tcp_rto;
8914 				}
8915 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8916 				    tcp_keepalive_killer,
8917 				    MSEC_TO_TICK(firetime));
8918 				tcp->tcp_ka_last_intrvl = firetime;
8919 				return;
8920 			}
8921 		}
8922 	} else {
8923 		tcp->tcp_ka_last_intrvl = 0;
8924 	}
8925 
8926 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8927 	if ((firetime = ka_intrvl - idletime) < 0) {
8928 		firetime = ka_intrvl;
8929 	}
8930 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8931 	    MSEC_TO_TICK(firetime));
8932 }
8933 
8934 int
8935 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8936 {
8937 	queue_t	*q = tcp->tcp_rq;
8938 	int32_t	mss = tcp->tcp_mss;
8939 	int	maxpsz;
8940 	conn_t	*connp = tcp->tcp_connp;
8941 
8942 	if (TCP_IS_DETACHED(tcp))
8943 		return (mss);
8944 	if (tcp->tcp_fused) {
8945 		maxpsz = tcp_fuse_maxpsz(tcp);
8946 		mss = INFPSZ;
8947 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8948 		/*
8949 		 * Set the sd_qn_maxpsz according to the socket send buffer
8950 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8951 		 * instruct the stream head to copyin user data into contiguous
8952 		 * kernel-allocated buffers without breaking it up into smaller
8953 		 * chunks.  We round up the buffer size to the nearest SMSS.
8954 		 */
8955 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8956 		if (tcp->tcp_kssl_ctx == NULL)
8957 			mss = INFPSZ;
8958 		else
8959 			mss = SSL3_MAX_RECORD_LEN;
8960 	} else {
8961 		/*
8962 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8963 		 * (and a multiple of the mss).  This instructs the stream
8964 		 * head to break down larger than SMSS writes into SMSS-
8965 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8966 		 */
8967 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8968 		maxpsz = tcp->tcp_maxpsz * mss;
8969 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8970 			maxpsz = tcp->tcp_xmit_hiwater/2;
8971 			/* Round up to nearest mss */
8972 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8973 		}
8974 	}
8975 
8976 	(void) proto_set_maxpsz(q, connp, maxpsz);
8977 	if (!(IPCL_IS_NONSTR(connp))) {
8978 		/* XXX do it in set_maxpsz()? */
8979 		tcp->tcp_wq->q_maxpsz = maxpsz;
8980 	}
8981 
8982 	if (set_maxblk)
8983 		(void) proto_set_tx_maxblk(q, connp, mss);
8984 	return (mss);
8985 }
8986 
8987 /*
8988  * Extract option values from a tcp header.  We put any found values into the
8989  * tcpopt struct and return a bitmask saying which options were found.
8990  */
8991 static int
8992 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8993 {
8994 	uchar_t		*endp;
8995 	int		len;
8996 	uint32_t	mss;
8997 	uchar_t		*up = (uchar_t *)tcph;
8998 	int		found = 0;
8999 	int32_t		sack_len;
9000 	tcp_seq		sack_begin, sack_end;
9001 	tcp_t		*tcp;
9002 
9003 	endp = up + TCP_HDR_LENGTH(tcph);
9004 	up += TCP_MIN_HEADER_LENGTH;
9005 	while (up < endp) {
9006 		len = endp - up;
9007 		switch (*up) {
9008 		case TCPOPT_EOL:
9009 			break;
9010 
9011 		case TCPOPT_NOP:
9012 			up++;
9013 			continue;
9014 
9015 		case TCPOPT_MAXSEG:
9016 			if (len < TCPOPT_MAXSEG_LEN ||
9017 			    up[1] != TCPOPT_MAXSEG_LEN)
9018 				break;
9019 
9020 			mss = BE16_TO_U16(up+2);
9021 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9022 			tcpopt->tcp_opt_mss = mss;
9023 			found |= TCP_OPT_MSS_PRESENT;
9024 
9025 			up += TCPOPT_MAXSEG_LEN;
9026 			continue;
9027 
9028 		case TCPOPT_WSCALE:
9029 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9030 				break;
9031 
9032 			if (up[2] > TCP_MAX_WINSHIFT)
9033 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9034 			else
9035 				tcpopt->tcp_opt_wscale = up[2];
9036 			found |= TCP_OPT_WSCALE_PRESENT;
9037 
9038 			up += TCPOPT_WS_LEN;
9039 			continue;
9040 
9041 		case TCPOPT_SACK_PERMITTED:
9042 			if (len < TCPOPT_SACK_OK_LEN ||
9043 			    up[1] != TCPOPT_SACK_OK_LEN)
9044 				break;
9045 			found |= TCP_OPT_SACK_OK_PRESENT;
9046 			up += TCPOPT_SACK_OK_LEN;
9047 			continue;
9048 
9049 		case TCPOPT_SACK:
9050 			if (len <= 2 || up[1] <= 2 || len < up[1])
9051 				break;
9052 
9053 			/* If TCP is not interested in SACK blks... */
9054 			if ((tcp = tcpopt->tcp) == NULL) {
9055 				up += up[1];
9056 				continue;
9057 			}
9058 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9059 			up += TCPOPT_HEADER_LEN;
9060 
9061 			/*
9062 			 * If the list is empty, allocate one and assume
9063 			 * nothing is sack'ed.
9064 			 */
9065 			ASSERT(tcp->tcp_sack_info != NULL);
9066 			if (tcp->tcp_notsack_list == NULL) {
9067 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9068 				    tcp->tcp_suna, tcp->tcp_snxt,
9069 				    &(tcp->tcp_num_notsack_blk),
9070 				    &(tcp->tcp_cnt_notsack_list));
9071 
9072 				/*
9073 				 * Make sure tcp_notsack_list is not NULL.
9074 				 * This happens when kmem_alloc(KM_NOSLEEP)
9075 				 * returns NULL.
9076 				 */
9077 				if (tcp->tcp_notsack_list == NULL) {
9078 					up += sack_len;
9079 					continue;
9080 				}
9081 				tcp->tcp_fack = tcp->tcp_suna;
9082 			}
9083 
9084 			while (sack_len > 0) {
9085 				if (up + 8 > endp) {
9086 					up = endp;
9087 					break;
9088 				}
9089 				sack_begin = BE32_TO_U32(up);
9090 				up += 4;
9091 				sack_end = BE32_TO_U32(up);
9092 				up += 4;
9093 				sack_len -= 8;
9094 				/*
9095 				 * Bounds checking.  Make sure the SACK
9096 				 * info is within tcp_suna and tcp_snxt.
9097 				 * If this SACK blk is out of bound, ignore
9098 				 * it but continue to parse the following
9099 				 * blks.
9100 				 */
9101 				if (SEQ_LEQ(sack_end, sack_begin) ||
9102 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9103 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9104 					continue;
9105 				}
9106 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9107 				    sack_begin, sack_end,
9108 				    &(tcp->tcp_num_notsack_blk),
9109 				    &(tcp->tcp_cnt_notsack_list));
9110 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9111 					tcp->tcp_fack = sack_end;
9112 				}
9113 			}
9114 			found |= TCP_OPT_SACK_PRESENT;
9115 			continue;
9116 
9117 		case TCPOPT_TSTAMP:
9118 			if (len < TCPOPT_TSTAMP_LEN ||
9119 			    up[1] != TCPOPT_TSTAMP_LEN)
9120 				break;
9121 
9122 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9123 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9124 
9125 			found |= TCP_OPT_TSTAMP_PRESENT;
9126 
9127 			up += TCPOPT_TSTAMP_LEN;
9128 			continue;
9129 
9130 		default:
9131 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9132 				break;
9133 			up += up[1];
9134 			continue;
9135 		}
9136 		break;
9137 	}
9138 	return (found);
9139 }
9140 
9141 /*
9142  * Set the mss associated with a particular tcp based on its current value,
9143  * and a new one passed in. Observe minimums and maximums, and reset
9144  * other state variables that we want to view as multiples of mss.
9145  *
9146  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9147  * highwater marks etc. need to be initialized or adjusted.
9148  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9149  *    packet arrives.
9150  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9151  *    ICMP6_PACKET_TOO_BIG arrives.
9152  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9153  *    to increase the MSS to use the extra bytes available.
9154  *
9155  * Callers except tcp_paws_check() ensure that they only reduce mss.
9156  */
9157 static void
9158 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9159 {
9160 	uint32_t	mss_max;
9161 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9162 
9163 	if (tcp->tcp_ipversion == IPV4_VERSION)
9164 		mss_max = tcps->tcps_mss_max_ipv4;
9165 	else
9166 		mss_max = tcps->tcps_mss_max_ipv6;
9167 
9168 	if (mss < tcps->tcps_mss_min)
9169 		mss = tcps->tcps_mss_min;
9170 	if (mss > mss_max)
9171 		mss = mss_max;
9172 	/*
9173 	 * Unless naglim has been set by our client to
9174 	 * a non-mss value, force naglim to track mss.
9175 	 * This can help to aggregate small writes.
9176 	 */
9177 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9178 		tcp->tcp_naglim = mss;
9179 	/*
9180 	 * TCP should be able to buffer at least 4 MSS data for obvious
9181 	 * performance reason.
9182 	 */
9183 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9184 		tcp->tcp_xmit_hiwater = mss << 2;
9185 
9186 	/*
9187 	 * Set the xmit_lowater to at least twice of MSS.
9188 	 */
9189 	if ((mss << 1) > tcp->tcp_xmit_lowater)
9190 		tcp->tcp_xmit_lowater = mss << 1;
9191 
9192 	if (do_ss) {
9193 		/*
9194 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9195 		 * changing due to a reduction in MTU, presumably as a
9196 		 * result of a new path component, reset cwnd to its
9197 		 * "initial" value, as a multiple of the new mss.
9198 		 */
9199 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9200 	} else {
9201 		/*
9202 		 * Called by tcp_paws_check(), the mss increased
9203 		 * marginally to allow use of space previously taken
9204 		 * by the timestamp option. It would be inappropriate
9205 		 * to apply slow start or tcp_init_cwnd values to
9206 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9207 		 */
9208 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9209 		tcp->tcp_cwnd_cnt = 0;
9210 	}
9211 	tcp->tcp_mss = mss;
9212 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9213 }
9214 
9215 /* For /dev/tcp aka AF_INET open */
9216 static int
9217 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9218 {
9219 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9220 }
9221 
9222 /* For /dev/tcp6 aka AF_INET6 open */
9223 static int
9224 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9225 {
9226 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9227 }
9228 
9229 static conn_t *
9230 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9231     boolean_t issocket, int *errorp)
9232 {
9233 	tcp_t		*tcp = NULL;
9234 	conn_t		*connp;
9235 	int		err;
9236 	zoneid_t	zoneid;
9237 	tcp_stack_t	*tcps;
9238 	squeue_t	*sqp;
9239 
9240 	ASSERT(errorp != NULL);
9241 	/*
9242 	 * Find the proper zoneid and netstack.
9243 	 */
9244 	/*
9245 	 * Special case for install: miniroot needs to be able to
9246 	 * access files via NFS as though it were always in the
9247 	 * global zone.
9248 	 */
9249 	if (credp == kcred && nfs_global_client_only != 0) {
9250 		zoneid = GLOBAL_ZONEID;
9251 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9252 		    netstack_tcp;
9253 		ASSERT(tcps != NULL);
9254 	} else {
9255 		netstack_t *ns;
9256 
9257 		ns = netstack_find_by_cred(credp);
9258 		ASSERT(ns != NULL);
9259 		tcps = ns->netstack_tcp;
9260 		ASSERT(tcps != NULL);
9261 
9262 		/*
9263 		 * For exclusive stacks we set the zoneid to zero
9264 		 * to make TCP operate as if in the global zone.
9265 		 */
9266 		if (tcps->tcps_netstack->netstack_stackid !=
9267 		    GLOBAL_NETSTACKID)
9268 			zoneid = GLOBAL_ZONEID;
9269 		else
9270 			zoneid = crgetzoneid(credp);
9271 	}
9272 	/*
9273 	 * For stackid zero this is done from strplumb.c, but
9274 	 * non-zero stackids are handled here.
9275 	 */
9276 	if (tcps->tcps_g_q == NULL &&
9277 	    tcps->tcps_netstack->netstack_stackid !=
9278 	    GLOBAL_NETSTACKID) {
9279 		tcp_g_q_setup(tcps);
9280 	}
9281 
9282 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9283 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9284 	/*
9285 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9286 	 * so we drop it by one.
9287 	 */
9288 	netstack_rele(tcps->tcps_netstack);
9289 	if (connp == NULL) {
9290 		*errorp = ENOSR;
9291 		return (NULL);
9292 	}
9293 	connp->conn_sqp = sqp;
9294 	connp->conn_initial_sqp = connp->conn_sqp;
9295 	tcp = connp->conn_tcp;
9296 
9297 	if (isv6) {
9298 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9299 		connp->conn_send = ip_output_v6;
9300 		connp->conn_af_isv6 = B_TRUE;
9301 		connp->conn_pkt_isv6 = B_TRUE;
9302 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9303 		tcp->tcp_ipversion = IPV6_VERSION;
9304 		tcp->tcp_family = AF_INET6;
9305 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9306 	} else {
9307 		connp->conn_flags |= IPCL_TCP4;
9308 		connp->conn_send = ip_output;
9309 		connp->conn_af_isv6 = B_FALSE;
9310 		connp->conn_pkt_isv6 = B_FALSE;
9311 		tcp->tcp_ipversion = IPV4_VERSION;
9312 		tcp->tcp_family = AF_INET;
9313 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9314 	}
9315 
9316 	/*
9317 	 * TCP keeps a copy of cred for cache locality reasons but
9318 	 * we put a reference only once. If connp->conn_cred
9319 	 * becomes invalid, tcp_cred should also be set to NULL.
9320 	 */
9321 	tcp->tcp_cred = connp->conn_cred = credp;
9322 	crhold(connp->conn_cred);
9323 	tcp->tcp_cpid = curproc->p_pid;
9324 	tcp->tcp_open_time = lbolt64;
9325 	connp->conn_zoneid = zoneid;
9326 	connp->conn_mlp_type = mlptSingle;
9327 	connp->conn_ulp_labeled = !is_system_labeled();
9328 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9329 	ASSERT(tcp->tcp_tcps == tcps);
9330 
9331 	/*
9332 	 * If the caller has the process-wide flag set, then default to MAC
9333 	 * exempt mode.  This allows read-down to unlabeled hosts.
9334 	 */
9335 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9336 		connp->conn_mac_exempt = B_TRUE;
9337 
9338 	connp->conn_dev = NULL;
9339 	if (issocket) {
9340 		connp->conn_flags |= IPCL_SOCKET;
9341 		tcp->tcp_issocket = 1;
9342 	}
9343 
9344 	/* Non-zero default values */
9345 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9346 
9347 	if (q == NULL) {
9348 		/*
9349 		 * Create a helper stream for non-STREAMS socket.
9350 		 */
9351 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9352 		if (err != 0) {
9353 			ip1dbg(("tcp_create_common: create of IP helper stream "
9354 			    "failed\n"));
9355 			CONN_DEC_REF(connp);
9356 			*errorp = err;
9357 			return (NULL);
9358 		}
9359 		q = connp->conn_rq;
9360 	}
9361 
9362 	SOCK_CONNID_INIT(tcp->tcp_connid);
9363 	err = tcp_init(tcp, q);
9364 	if (err != 0) {
9365 		CONN_DEC_REF(connp);
9366 		*errorp = err;
9367 		return (NULL);
9368 	}
9369 
9370 	return (connp);
9371 }
9372 
9373 static int
9374 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9375     boolean_t isv6)
9376 {
9377 	tcp_t		*tcp = NULL;
9378 	conn_t		*connp = NULL;
9379 	int		err;
9380 	vmem_t		*minor_arena = NULL;
9381 	dev_t		conn_dev;
9382 	boolean_t	issocket;
9383 
9384 	if (q->q_ptr != NULL)
9385 		return (0);
9386 
9387 	if (sflag == MODOPEN)
9388 		return (EINVAL);
9389 
9390 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9391 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9392 		minor_arena = ip_minor_arena_la;
9393 	} else {
9394 		/*
9395 		 * Either minor numbers in the large arena were exhausted
9396 		 * or a non socket application is doing the open.
9397 		 * Try to allocate from the small arena.
9398 		 */
9399 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9400 			return (EBUSY);
9401 		}
9402 		minor_arena = ip_minor_arena_sa;
9403 	}
9404 
9405 	ASSERT(minor_arena != NULL);
9406 
9407 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9408 
9409 	if (flag & SO_FALLBACK) {
9410 		/*
9411 		 * Non streams socket needs a stream to fallback to
9412 		 */
9413 		RD(q)->q_ptr = (void *)conn_dev;
9414 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9415 		WR(q)->q_ptr = (void *)minor_arena;
9416 		qprocson(q);
9417 		return (0);
9418 	} else if (flag & SO_ACCEPTOR) {
9419 		q->q_qinfo = &tcp_acceptor_rinit;
9420 		/*
9421 		 * the conn_dev and minor_arena will be subsequently used by
9422 		 * tcp_wput_accept() and tcp_tpi_close_accept() to figure out
9423 		 * the minor device number for this connection from the q_ptr.
9424 		 */
9425 		RD(q)->q_ptr = (void *)conn_dev;
9426 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9427 		WR(q)->q_ptr = (void *)minor_arena;
9428 		qprocson(q);
9429 		return (0);
9430 	}
9431 
9432 	issocket = flag & SO_SOCKSTR;
9433 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9434 
9435 	if (connp == NULL) {
9436 		inet_minor_free(minor_arena, conn_dev);
9437 		q->q_ptr = WR(q)->q_ptr = NULL;
9438 		return (err);
9439 	}
9440 
9441 	q->q_ptr = WR(q)->q_ptr = connp;
9442 
9443 	connp->conn_dev = conn_dev;
9444 	connp->conn_minor_arena = minor_arena;
9445 
9446 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9447 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9448 
9449 	tcp = connp->conn_tcp;
9450 
9451 	if (issocket) {
9452 		WR(q)->q_qinfo = &tcp_sock_winit;
9453 	} else {
9454 #ifdef  _ILP32
9455 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9456 #else
9457 		tcp->tcp_acceptor_id = conn_dev;
9458 #endif  /* _ILP32 */
9459 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9460 	}
9461 
9462 	/*
9463 	 * Put the ref for TCP. Ref for IP was already put
9464 	 * by ipcl_conn_create. Also Make the conn_t globally
9465 	 * visible to walkers
9466 	 */
9467 	mutex_enter(&connp->conn_lock);
9468 	CONN_INC_REF_LOCKED(connp);
9469 	ASSERT(connp->conn_ref == 2);
9470 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9471 	mutex_exit(&connp->conn_lock);
9472 
9473 	qprocson(q);
9474 	return (0);
9475 }
9476 
9477 /*
9478  * Some TCP options can be "set" by requesting them in the option
9479  * buffer. This is needed for XTI feature test though we do not
9480  * allow it in general. We interpret that this mechanism is more
9481  * applicable to OSI protocols and need not be allowed in general.
9482  * This routine filters out options for which it is not allowed (most)
9483  * and lets through those (few) for which it is. [ The XTI interface
9484  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9485  * ever implemented will have to be allowed here ].
9486  */
9487 static boolean_t
9488 tcp_allow_connopt_set(int level, int name)
9489 {
9490 
9491 	switch (level) {
9492 	case IPPROTO_TCP:
9493 		switch (name) {
9494 		case TCP_NODELAY:
9495 			return (B_TRUE);
9496 		default:
9497 			return (B_FALSE);
9498 		}
9499 		/*NOTREACHED*/
9500 	default:
9501 		return (B_FALSE);
9502 	}
9503 	/*NOTREACHED*/
9504 }
9505 
9506 /*
9507  * this routine gets default values of certain options whose default
9508  * values are maintained by protocol specific code
9509  */
9510 /* ARGSUSED */
9511 int
9512 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9513 {
9514 	int32_t	*i1 = (int32_t *)ptr;
9515 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9516 
9517 	switch (level) {
9518 	case IPPROTO_TCP:
9519 		switch (name) {
9520 		case TCP_NOTIFY_THRESHOLD:
9521 			*i1 = tcps->tcps_ip_notify_interval;
9522 			break;
9523 		case TCP_ABORT_THRESHOLD:
9524 			*i1 = tcps->tcps_ip_abort_interval;
9525 			break;
9526 		case TCP_CONN_NOTIFY_THRESHOLD:
9527 			*i1 = tcps->tcps_ip_notify_cinterval;
9528 			break;
9529 		case TCP_CONN_ABORT_THRESHOLD:
9530 			*i1 = tcps->tcps_ip_abort_cinterval;
9531 			break;
9532 		default:
9533 			return (-1);
9534 		}
9535 		break;
9536 	case IPPROTO_IP:
9537 		switch (name) {
9538 		case IP_TTL:
9539 			*i1 = tcps->tcps_ipv4_ttl;
9540 			break;
9541 		default:
9542 			return (-1);
9543 		}
9544 		break;
9545 	case IPPROTO_IPV6:
9546 		switch (name) {
9547 		case IPV6_UNICAST_HOPS:
9548 			*i1 = tcps->tcps_ipv6_hoplimit;
9549 			break;
9550 		default:
9551 			return (-1);
9552 		}
9553 		break;
9554 	default:
9555 		return (-1);
9556 	}
9557 	return (sizeof (int));
9558 }
9559 
9560 static int
9561 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9562 {
9563 	int		*i1 = (int *)ptr;
9564 	tcp_t		*tcp = connp->conn_tcp;
9565 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9566 
9567 	switch (level) {
9568 	case SOL_SOCKET:
9569 		switch (name) {
9570 		case SO_LINGER:	{
9571 			struct linger *lgr = (struct linger *)ptr;
9572 
9573 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9574 			lgr->l_linger = tcp->tcp_lingertime;
9575 			}
9576 			return (sizeof (struct linger));
9577 		case SO_DEBUG:
9578 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9579 			break;
9580 		case SO_KEEPALIVE:
9581 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9582 			break;
9583 		case SO_DONTROUTE:
9584 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9585 			break;
9586 		case SO_USELOOPBACK:
9587 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9588 			break;
9589 		case SO_BROADCAST:
9590 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9591 			break;
9592 		case SO_REUSEADDR:
9593 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9594 			break;
9595 		case SO_OOBINLINE:
9596 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9597 			break;
9598 		case SO_DGRAM_ERRIND:
9599 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9600 			break;
9601 		case SO_TYPE:
9602 			*i1 = SOCK_STREAM;
9603 			break;
9604 		case SO_SNDBUF:
9605 			*i1 = tcp->tcp_xmit_hiwater;
9606 			break;
9607 		case SO_RCVBUF:
9608 			*i1 = tcp->tcp_recv_hiwater;
9609 			break;
9610 		case SO_SND_COPYAVOID:
9611 			*i1 = tcp->tcp_snd_zcopy_on ?
9612 			    SO_SND_COPYAVOID : 0;
9613 			break;
9614 		case SO_ALLZONES:
9615 			*i1 = connp->conn_allzones ? 1 : 0;
9616 			break;
9617 		case SO_ANON_MLP:
9618 			*i1 = connp->conn_anon_mlp;
9619 			break;
9620 		case SO_MAC_EXEMPT:
9621 			*i1 = connp->conn_mac_exempt;
9622 			break;
9623 		case SO_EXCLBIND:
9624 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9625 			break;
9626 		case SO_PROTOTYPE:
9627 			*i1 = IPPROTO_TCP;
9628 			break;
9629 		case SO_DOMAIN:
9630 			*i1 = tcp->tcp_family;
9631 			break;
9632 		case SO_ACCEPTCONN:
9633 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9634 		default:
9635 			return (-1);
9636 		}
9637 		break;
9638 	case IPPROTO_TCP:
9639 		switch (name) {
9640 		case TCP_NODELAY:
9641 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9642 			break;
9643 		case TCP_MAXSEG:
9644 			*i1 = tcp->tcp_mss;
9645 			break;
9646 		case TCP_NOTIFY_THRESHOLD:
9647 			*i1 = (int)tcp->tcp_first_timer_threshold;
9648 			break;
9649 		case TCP_ABORT_THRESHOLD:
9650 			*i1 = tcp->tcp_second_timer_threshold;
9651 			break;
9652 		case TCP_CONN_NOTIFY_THRESHOLD:
9653 			*i1 = tcp->tcp_first_ctimer_threshold;
9654 			break;
9655 		case TCP_CONN_ABORT_THRESHOLD:
9656 			*i1 = tcp->tcp_second_ctimer_threshold;
9657 			break;
9658 		case TCP_RECVDSTADDR:
9659 			*i1 = tcp->tcp_recvdstaddr;
9660 			break;
9661 		case TCP_ANONPRIVBIND:
9662 			*i1 = tcp->tcp_anon_priv_bind;
9663 			break;
9664 		case TCP_EXCLBIND:
9665 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9666 			break;
9667 		case TCP_INIT_CWND:
9668 			*i1 = tcp->tcp_init_cwnd;
9669 			break;
9670 		case TCP_KEEPALIVE_THRESHOLD:
9671 			*i1 = tcp->tcp_ka_interval;
9672 			break;
9673 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9674 			*i1 = tcp->tcp_ka_abort_thres;
9675 			break;
9676 		case TCP_CORK:
9677 			*i1 = tcp->tcp_cork;
9678 			break;
9679 		default:
9680 			return (-1);
9681 		}
9682 		break;
9683 	case IPPROTO_IP:
9684 		if (tcp->tcp_family != AF_INET)
9685 			return (-1);
9686 		switch (name) {
9687 		case IP_OPTIONS:
9688 		case T_IP_OPTIONS: {
9689 			/*
9690 			 * This is compatible with BSD in that in only return
9691 			 * the reverse source route with the final destination
9692 			 * as the last entry. The first 4 bytes of the option
9693 			 * will contain the final destination.
9694 			 */
9695 			int	opt_len;
9696 
9697 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9698 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9699 			ASSERT(opt_len >= 0);
9700 			/* Caller ensures enough space */
9701 			if (opt_len > 0) {
9702 				/*
9703 				 * TODO: Do we have to handle getsockopt on an
9704 				 * initiator as well?
9705 				 */
9706 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9707 			}
9708 			return (0);
9709 			}
9710 		case IP_TOS:
9711 		case T_IP_TOS:
9712 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9713 			break;
9714 		case IP_TTL:
9715 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9716 			break;
9717 		case IP_NEXTHOP:
9718 			/* Handled at IP level */
9719 			return (-EINVAL);
9720 		default:
9721 			return (-1);
9722 		}
9723 		break;
9724 	case IPPROTO_IPV6:
9725 		/*
9726 		 * IPPROTO_IPV6 options are only supported for sockets
9727 		 * that are using IPv6 on the wire.
9728 		 */
9729 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9730 			return (-1);
9731 		}
9732 		switch (name) {
9733 		case IPV6_UNICAST_HOPS:
9734 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9735 			break;	/* goto sizeof (int) option return */
9736 		case IPV6_BOUND_IF:
9737 			/* Zero if not set */
9738 			*i1 = tcp->tcp_bound_if;
9739 			break;	/* goto sizeof (int) option return */
9740 		case IPV6_RECVPKTINFO:
9741 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9742 				*i1 = 1;
9743 			else
9744 				*i1 = 0;
9745 			break;	/* goto sizeof (int) option return */
9746 		case IPV6_RECVTCLASS:
9747 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9748 				*i1 = 1;
9749 			else
9750 				*i1 = 0;
9751 			break;	/* goto sizeof (int) option return */
9752 		case IPV6_RECVHOPLIMIT:
9753 			if (tcp->tcp_ipv6_recvancillary &
9754 			    TCP_IPV6_RECVHOPLIMIT)
9755 				*i1 = 1;
9756 			else
9757 				*i1 = 0;
9758 			break;	/* goto sizeof (int) option return */
9759 		case IPV6_RECVHOPOPTS:
9760 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9761 				*i1 = 1;
9762 			else
9763 				*i1 = 0;
9764 			break;	/* goto sizeof (int) option return */
9765 		case IPV6_RECVDSTOPTS:
9766 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9767 				*i1 = 1;
9768 			else
9769 				*i1 = 0;
9770 			break;	/* goto sizeof (int) option return */
9771 		case _OLD_IPV6_RECVDSTOPTS:
9772 			if (tcp->tcp_ipv6_recvancillary &
9773 			    TCP_OLD_IPV6_RECVDSTOPTS)
9774 				*i1 = 1;
9775 			else
9776 				*i1 = 0;
9777 			break;	/* goto sizeof (int) option return */
9778 		case IPV6_RECVRTHDR:
9779 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9780 				*i1 = 1;
9781 			else
9782 				*i1 = 0;
9783 			break;	/* goto sizeof (int) option return */
9784 		case IPV6_RECVRTHDRDSTOPTS:
9785 			if (tcp->tcp_ipv6_recvancillary &
9786 			    TCP_IPV6_RECVRTDSTOPTS)
9787 				*i1 = 1;
9788 			else
9789 				*i1 = 0;
9790 			break;	/* goto sizeof (int) option return */
9791 		case IPV6_PKTINFO: {
9792 			/* XXX assumes that caller has room for max size! */
9793 			struct in6_pktinfo *pkti;
9794 
9795 			pkti = (struct in6_pktinfo *)ptr;
9796 			if (ipp->ipp_fields & IPPF_IFINDEX)
9797 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9798 			else
9799 				pkti->ipi6_ifindex = 0;
9800 			if (ipp->ipp_fields & IPPF_ADDR)
9801 				pkti->ipi6_addr = ipp->ipp_addr;
9802 			else
9803 				pkti->ipi6_addr = ipv6_all_zeros;
9804 			return (sizeof (struct in6_pktinfo));
9805 		}
9806 		case IPV6_TCLASS:
9807 			if (ipp->ipp_fields & IPPF_TCLASS)
9808 				*i1 = ipp->ipp_tclass;
9809 			else
9810 				*i1 = IPV6_FLOW_TCLASS(
9811 				    IPV6_DEFAULT_VERS_AND_FLOW);
9812 			break;	/* goto sizeof (int) option return */
9813 		case IPV6_NEXTHOP: {
9814 			sin6_t *sin6 = (sin6_t *)ptr;
9815 
9816 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9817 				return (0);
9818 			*sin6 = sin6_null;
9819 			sin6->sin6_family = AF_INET6;
9820 			sin6->sin6_addr = ipp->ipp_nexthop;
9821 			return (sizeof (sin6_t));
9822 		}
9823 		case IPV6_HOPOPTS:
9824 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9825 				return (0);
9826 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9827 				return (0);
9828 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9829 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9830 			if (tcp->tcp_label_len > 0) {
9831 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9832 				ptr[1] = (ipp->ipp_hopoptslen -
9833 				    tcp->tcp_label_len + 7) / 8 - 1;
9834 			}
9835 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9836 		case IPV6_RTHDRDSTOPTS:
9837 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9838 				return (0);
9839 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9840 			return (ipp->ipp_rtdstoptslen);
9841 		case IPV6_RTHDR:
9842 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9843 				return (0);
9844 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9845 			return (ipp->ipp_rthdrlen);
9846 		case IPV6_DSTOPTS:
9847 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9848 				return (0);
9849 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9850 			return (ipp->ipp_dstoptslen);
9851 		case IPV6_SRC_PREFERENCES:
9852 			return (ip6_get_src_preferences(connp,
9853 			    (uint32_t *)ptr));
9854 		case IPV6_PATHMTU: {
9855 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9856 
9857 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9858 				return (-1);
9859 
9860 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9861 			    connp->conn_fport, mtuinfo,
9862 			    connp->conn_netstack));
9863 		}
9864 		default:
9865 			return (-1);
9866 		}
9867 		break;
9868 	default:
9869 		return (-1);
9870 	}
9871 	return (sizeof (int));
9872 }
9873 
9874 /*
9875  * TCP routine to get the values of options.
9876  */
9877 int
9878 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9879 {
9880 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9881 }
9882 
9883 /* returns UNIX error, the optlen is a value-result arg */
9884 int
9885 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9886     void *optvalp, socklen_t *optlen, cred_t *cr)
9887 {
9888 	conn_t		*connp = (conn_t *)proto_handle;
9889 	squeue_t	*sqp = connp->conn_sqp;
9890 	int		error;
9891 	t_uscalar_t	max_optbuf_len;
9892 	void		*optvalp_buf;
9893 	int		len;
9894 
9895 	ASSERT(connp->conn_upper_handle != NULL);
9896 
9897 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9898 	    tcp_opt_obj.odb_opt_des_arr,
9899 	    tcp_opt_obj.odb_opt_arr_cnt,
9900 	    tcp_opt_obj.odb_topmost_tpiprovider,
9901 	    B_FALSE, B_TRUE, cr);
9902 	if (error != 0) {
9903 		if (error < 0) {
9904 			error = proto_tlitosyserr(-error);
9905 		}
9906 		return (error);
9907 	}
9908 
9909 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9910 
9911 	error = squeue_synch_enter(sqp, connp, NULL);
9912 	if (error == ENOMEM) {
9913 		return (ENOMEM);
9914 	}
9915 
9916 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9917 	squeue_synch_exit(sqp, connp);
9918 
9919 	if (len < 0) {
9920 		/*
9921 		 * Pass on to IP
9922 		 */
9923 		kmem_free(optvalp_buf, max_optbuf_len);
9924 		return (ip_get_options(connp, level, option_name,
9925 		    optvalp, optlen, cr));
9926 	} else {
9927 		/*
9928 		 * update optlen and copy option value
9929 		 */
9930 		t_uscalar_t size = MIN(len, *optlen);
9931 		bcopy(optvalp_buf, optvalp, size);
9932 		bcopy(&size, optlen, sizeof (size));
9933 
9934 		kmem_free(optvalp_buf, max_optbuf_len);
9935 		return (0);
9936 	}
9937 }
9938 
9939 /*
9940  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9941  * Parameters are assumed to be verified by the caller.
9942  */
9943 /* ARGSUSED */
9944 int
9945 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9946     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9947     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9948 {
9949 	tcp_t	*tcp = connp->conn_tcp;
9950 	int	*i1 = (int *)invalp;
9951 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9952 	boolean_t checkonly;
9953 	int	reterr;
9954 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9955 
9956 	switch (optset_context) {
9957 	case SETFN_OPTCOM_CHECKONLY:
9958 		checkonly = B_TRUE;
9959 		/*
9960 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9961 		 * inlen != 0 implies value supplied and
9962 		 * 	we have to "pretend" to set it.
9963 		 * inlen == 0 implies that there is no
9964 		 * 	value part in T_CHECK request and just validation
9965 		 * done elsewhere should be enough, we just return here.
9966 		 */
9967 		if (inlen == 0) {
9968 			*outlenp = 0;
9969 			return (0);
9970 		}
9971 		break;
9972 	case SETFN_OPTCOM_NEGOTIATE:
9973 		checkonly = B_FALSE;
9974 		break;
9975 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9976 	case SETFN_CONN_NEGOTIATE:
9977 		checkonly = B_FALSE;
9978 		/*
9979 		 * Negotiating local and "association-related" options
9980 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9981 		 * primitives is allowed by XTI, but we choose
9982 		 * to not implement this style negotiation for Internet
9983 		 * protocols (We interpret it is a must for OSI world but
9984 		 * optional for Internet protocols) for all options.
9985 		 * [ Will do only for the few options that enable test
9986 		 * suites that our XTI implementation of this feature
9987 		 * works for transports that do allow it ]
9988 		 */
9989 		if (!tcp_allow_connopt_set(level, name)) {
9990 			*outlenp = 0;
9991 			return (EINVAL);
9992 		}
9993 		break;
9994 	default:
9995 		/*
9996 		 * We should never get here
9997 		 */
9998 		*outlenp = 0;
9999 		return (EINVAL);
10000 	}
10001 
10002 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10003 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10004 
10005 	/*
10006 	 * For TCP, we should have no ancillary data sent down
10007 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10008 	 * has to be zero.
10009 	 */
10010 	ASSERT(thisdg_attrs == NULL);
10011 
10012 	/*
10013 	 * For fixed length options, no sanity check
10014 	 * of passed in length is done. It is assumed *_optcom_req()
10015 	 * routines do the right thing.
10016 	 */
10017 	switch (level) {
10018 	case SOL_SOCKET:
10019 		switch (name) {
10020 		case SO_LINGER: {
10021 			struct linger *lgr = (struct linger *)invalp;
10022 
10023 			if (!checkonly) {
10024 				if (lgr->l_onoff) {
10025 					tcp->tcp_linger = 1;
10026 					tcp->tcp_lingertime = lgr->l_linger;
10027 				} else {
10028 					tcp->tcp_linger = 0;
10029 					tcp->tcp_lingertime = 0;
10030 				}
10031 				/* struct copy */
10032 				*(struct linger *)outvalp = *lgr;
10033 			} else {
10034 				if (!lgr->l_onoff) {
10035 					((struct linger *)
10036 					    outvalp)->l_onoff = 0;
10037 					((struct linger *)
10038 					    outvalp)->l_linger = 0;
10039 				} else {
10040 					/* struct copy */
10041 					*(struct linger *)outvalp = *lgr;
10042 				}
10043 			}
10044 			*outlenp = sizeof (struct linger);
10045 			return (0);
10046 		}
10047 		case SO_DEBUG:
10048 			if (!checkonly)
10049 				tcp->tcp_debug = onoff;
10050 			break;
10051 		case SO_KEEPALIVE:
10052 			if (checkonly) {
10053 				/* check only case */
10054 				break;
10055 			}
10056 
10057 			if (!onoff) {
10058 				if (tcp->tcp_ka_enabled) {
10059 					if (tcp->tcp_ka_tid != 0) {
10060 						(void) TCP_TIMER_CANCEL(tcp,
10061 						    tcp->tcp_ka_tid);
10062 						tcp->tcp_ka_tid = 0;
10063 					}
10064 					tcp->tcp_ka_enabled = 0;
10065 				}
10066 				break;
10067 			}
10068 			if (!tcp->tcp_ka_enabled) {
10069 				/* Crank up the keepalive timer */
10070 				tcp->tcp_ka_last_intrvl = 0;
10071 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10072 				    tcp_keepalive_killer,
10073 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10074 				tcp->tcp_ka_enabled = 1;
10075 			}
10076 			break;
10077 		case SO_DONTROUTE:
10078 			/*
10079 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10080 			 * only of interest to IP.  We track them here only so
10081 			 * that we can report their current value.
10082 			 */
10083 			if (!checkonly) {
10084 				tcp->tcp_dontroute = onoff;
10085 				tcp->tcp_connp->conn_dontroute = onoff;
10086 			}
10087 			break;
10088 		case SO_USELOOPBACK:
10089 			if (!checkonly) {
10090 				tcp->tcp_useloopback = onoff;
10091 				tcp->tcp_connp->conn_loopback = onoff;
10092 			}
10093 			break;
10094 		case SO_BROADCAST:
10095 			if (!checkonly) {
10096 				tcp->tcp_broadcast = onoff;
10097 				tcp->tcp_connp->conn_broadcast = onoff;
10098 			}
10099 			break;
10100 		case SO_REUSEADDR:
10101 			if (!checkonly) {
10102 				tcp->tcp_reuseaddr = onoff;
10103 				tcp->tcp_connp->conn_reuseaddr = onoff;
10104 			}
10105 			break;
10106 		case SO_OOBINLINE:
10107 			if (!checkonly) {
10108 				tcp->tcp_oobinline = onoff;
10109 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10110 					proto_set_rx_oob_opt(connp, onoff);
10111 			}
10112 			break;
10113 		case SO_DGRAM_ERRIND:
10114 			if (!checkonly)
10115 				tcp->tcp_dgram_errind = onoff;
10116 			break;
10117 		case SO_SNDBUF: {
10118 			if (*i1 > tcps->tcps_max_buf) {
10119 				*outlenp = 0;
10120 				return (ENOBUFS);
10121 			}
10122 			if (checkonly)
10123 				break;
10124 
10125 			tcp->tcp_xmit_hiwater = *i1;
10126 			if (tcps->tcps_snd_lowat_fraction != 0)
10127 				tcp->tcp_xmit_lowater =
10128 				    tcp->tcp_xmit_hiwater /
10129 				    tcps->tcps_snd_lowat_fraction;
10130 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10131 			/*
10132 			 * If we are flow-controlled, recheck the condition.
10133 			 * There are apps that increase SO_SNDBUF size when
10134 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10135 			 * control condition to be lifted right away.
10136 			 */
10137 			mutex_enter(&tcp->tcp_non_sq_lock);
10138 			if (tcp->tcp_flow_stopped &&
10139 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10140 				tcp_clrqfull(tcp);
10141 			}
10142 			mutex_exit(&tcp->tcp_non_sq_lock);
10143 			break;
10144 		}
10145 		case SO_RCVBUF:
10146 			if (*i1 > tcps->tcps_max_buf) {
10147 				*outlenp = 0;
10148 				return (ENOBUFS);
10149 			}
10150 			/* Silently ignore zero */
10151 			if (!checkonly && *i1 != 0) {
10152 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10153 				(void) tcp_rwnd_set(tcp, *i1);
10154 			}
10155 			/*
10156 			 * XXX should we return the rwnd here
10157 			 * and tcp_opt_get ?
10158 			 */
10159 			break;
10160 		case SO_SND_COPYAVOID:
10161 			if (!checkonly) {
10162 				/* we only allow enable at most once for now */
10163 				if (tcp->tcp_loopback ||
10164 				    (tcp->tcp_kssl_ctx != NULL) ||
10165 				    (!tcp->tcp_snd_zcopy_aware &&
10166 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10167 					*outlenp = 0;
10168 					return (EOPNOTSUPP);
10169 				}
10170 				tcp->tcp_snd_zcopy_aware = 1;
10171 			}
10172 			break;
10173 		case SO_RCVTIMEO:
10174 		case SO_SNDTIMEO:
10175 			/*
10176 			 * Pass these two options in order for third part
10177 			 * protocol usage. Here just return directly.
10178 			 */
10179 			return (0);
10180 		case SO_ALLZONES:
10181 			/* Pass option along to IP level for handling */
10182 			return (-EINVAL);
10183 		case SO_ANON_MLP:
10184 			/* Pass option along to IP level for handling */
10185 			return (-EINVAL);
10186 		case SO_MAC_EXEMPT:
10187 			/* Pass option along to IP level for handling */
10188 			return (-EINVAL);
10189 		case SO_EXCLBIND:
10190 			if (!checkonly)
10191 				tcp->tcp_exclbind = onoff;
10192 			break;
10193 		default:
10194 			*outlenp = 0;
10195 			return (EINVAL);
10196 		}
10197 		break;
10198 	case IPPROTO_TCP:
10199 		switch (name) {
10200 		case TCP_NODELAY:
10201 			if (!checkonly)
10202 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10203 			break;
10204 		case TCP_NOTIFY_THRESHOLD:
10205 			if (!checkonly)
10206 				tcp->tcp_first_timer_threshold = *i1;
10207 			break;
10208 		case TCP_ABORT_THRESHOLD:
10209 			if (!checkonly)
10210 				tcp->tcp_second_timer_threshold = *i1;
10211 			break;
10212 		case TCP_CONN_NOTIFY_THRESHOLD:
10213 			if (!checkonly)
10214 				tcp->tcp_first_ctimer_threshold = *i1;
10215 			break;
10216 		case TCP_CONN_ABORT_THRESHOLD:
10217 			if (!checkonly)
10218 				tcp->tcp_second_ctimer_threshold = *i1;
10219 			break;
10220 		case TCP_RECVDSTADDR:
10221 			if (tcp->tcp_state > TCPS_LISTEN)
10222 				return (EOPNOTSUPP);
10223 			if (!checkonly)
10224 				tcp->tcp_recvdstaddr = onoff;
10225 			break;
10226 		case TCP_ANONPRIVBIND:
10227 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10228 			    IPPROTO_TCP)) != 0) {
10229 				*outlenp = 0;
10230 				return (reterr);
10231 			}
10232 			if (!checkonly) {
10233 				tcp->tcp_anon_priv_bind = onoff;
10234 			}
10235 			break;
10236 		case TCP_EXCLBIND:
10237 			if (!checkonly)
10238 				tcp->tcp_exclbind = onoff;
10239 			break;	/* goto sizeof (int) option return */
10240 		case TCP_INIT_CWND: {
10241 			uint32_t init_cwnd = *((uint32_t *)invalp);
10242 
10243 			if (checkonly)
10244 				break;
10245 
10246 			/*
10247 			 * Only allow socket with network configuration
10248 			 * privilege to set the initial cwnd to be larger
10249 			 * than allowed by RFC 3390.
10250 			 */
10251 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10252 				tcp->tcp_init_cwnd = init_cwnd;
10253 				break;
10254 			}
10255 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10256 				*outlenp = 0;
10257 				return (reterr);
10258 			}
10259 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10260 				*outlenp = 0;
10261 				return (EINVAL);
10262 			}
10263 			tcp->tcp_init_cwnd = init_cwnd;
10264 			break;
10265 		}
10266 		case TCP_KEEPALIVE_THRESHOLD:
10267 			if (checkonly)
10268 				break;
10269 
10270 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10271 			    *i1 > tcps->tcps_keepalive_interval_high) {
10272 				*outlenp = 0;
10273 				return (EINVAL);
10274 			}
10275 			if (*i1 != tcp->tcp_ka_interval) {
10276 				tcp->tcp_ka_interval = *i1;
10277 				/*
10278 				 * Check if we need to restart the
10279 				 * keepalive timer.
10280 				 */
10281 				if (tcp->tcp_ka_tid != 0) {
10282 					ASSERT(tcp->tcp_ka_enabled);
10283 					(void) TCP_TIMER_CANCEL(tcp,
10284 					    tcp->tcp_ka_tid);
10285 					tcp->tcp_ka_last_intrvl = 0;
10286 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10287 					    tcp_keepalive_killer,
10288 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10289 				}
10290 			}
10291 			break;
10292 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10293 			if (!checkonly) {
10294 				if (*i1 <
10295 				    tcps->tcps_keepalive_abort_interval_low ||
10296 				    *i1 >
10297 				    tcps->tcps_keepalive_abort_interval_high) {
10298 					*outlenp = 0;
10299 					return (EINVAL);
10300 				}
10301 				tcp->tcp_ka_abort_thres = *i1;
10302 			}
10303 			break;
10304 		case TCP_CORK:
10305 			if (!checkonly) {
10306 				/*
10307 				 * if tcp->tcp_cork was set and is now
10308 				 * being unset, we have to make sure that
10309 				 * the remaining data gets sent out. Also
10310 				 * unset tcp->tcp_cork so that tcp_wput_data()
10311 				 * can send data even if it is less than mss
10312 				 */
10313 				if (tcp->tcp_cork && onoff == 0 &&
10314 				    tcp->tcp_unsent > 0) {
10315 					tcp->tcp_cork = B_FALSE;
10316 					tcp_wput_data(tcp, NULL, B_FALSE);
10317 				}
10318 				tcp->tcp_cork = onoff;
10319 			}
10320 			break;
10321 		default:
10322 			*outlenp = 0;
10323 			return (EINVAL);
10324 		}
10325 		break;
10326 	case IPPROTO_IP:
10327 		if (tcp->tcp_family != AF_INET) {
10328 			*outlenp = 0;
10329 			return (ENOPROTOOPT);
10330 		}
10331 		switch (name) {
10332 		case IP_OPTIONS:
10333 		case T_IP_OPTIONS:
10334 			reterr = tcp_opt_set_header(tcp, checkonly,
10335 			    invalp, inlen);
10336 			if (reterr) {
10337 				*outlenp = 0;
10338 				return (reterr);
10339 			}
10340 			/* OK return - copy input buffer into output buffer */
10341 			if (invalp != outvalp) {
10342 				/* don't trust bcopy for identical src/dst */
10343 				bcopy(invalp, outvalp, inlen);
10344 			}
10345 			*outlenp = inlen;
10346 			return (0);
10347 		case IP_TOS:
10348 		case T_IP_TOS:
10349 			if (!checkonly) {
10350 				tcp->tcp_ipha->ipha_type_of_service =
10351 				    (uchar_t)*i1;
10352 				tcp->tcp_tos = (uchar_t)*i1;
10353 			}
10354 			break;
10355 		case IP_TTL:
10356 			if (!checkonly) {
10357 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10358 				tcp->tcp_ttl = (uchar_t)*i1;
10359 			}
10360 			break;
10361 		case IP_BOUND_IF:
10362 		case IP_NEXTHOP:
10363 			/* Handled at the IP level */
10364 			return (-EINVAL);
10365 		case IP_SEC_OPT:
10366 			/*
10367 			 * We should not allow policy setting after
10368 			 * we start listening for connections.
10369 			 */
10370 			if (tcp->tcp_state == TCPS_LISTEN) {
10371 				return (EINVAL);
10372 			} else {
10373 				/* Handled at the IP level */
10374 				return (-EINVAL);
10375 			}
10376 		default:
10377 			*outlenp = 0;
10378 			return (EINVAL);
10379 		}
10380 		break;
10381 	case IPPROTO_IPV6: {
10382 		ip6_pkt_t		*ipp;
10383 
10384 		/*
10385 		 * IPPROTO_IPV6 options are only supported for sockets
10386 		 * that are using IPv6 on the wire.
10387 		 */
10388 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10389 			*outlenp = 0;
10390 			return (ENOPROTOOPT);
10391 		}
10392 		/*
10393 		 * Only sticky options; no ancillary data
10394 		 */
10395 		ipp = &tcp->tcp_sticky_ipp;
10396 
10397 		switch (name) {
10398 		case IPV6_UNICAST_HOPS:
10399 			/* -1 means use default */
10400 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10401 				*outlenp = 0;
10402 				return (EINVAL);
10403 			}
10404 			if (!checkonly) {
10405 				if (*i1 == -1) {
10406 					tcp->tcp_ip6h->ip6_hops =
10407 					    ipp->ipp_unicast_hops =
10408 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10409 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10410 					/* Pass modified value to IP. */
10411 					*i1 = tcp->tcp_ip6h->ip6_hops;
10412 				} else {
10413 					tcp->tcp_ip6h->ip6_hops =
10414 					    ipp->ipp_unicast_hops =
10415 					    (uint8_t)*i1;
10416 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10417 				}
10418 				reterr = tcp_build_hdrs(tcp);
10419 				if (reterr != 0)
10420 					return (reterr);
10421 			}
10422 			break;
10423 		case IPV6_BOUND_IF:
10424 			if (!checkonly) {
10425 				tcp->tcp_bound_if = *i1;
10426 				PASS_OPT_TO_IP(connp);
10427 			}
10428 			break;
10429 		/*
10430 		 * Set boolean switches for ancillary data delivery
10431 		 */
10432 		case IPV6_RECVPKTINFO:
10433 			if (!checkonly) {
10434 				if (onoff)
10435 					tcp->tcp_ipv6_recvancillary |=
10436 					    TCP_IPV6_RECVPKTINFO;
10437 				else
10438 					tcp->tcp_ipv6_recvancillary &=
10439 					    ~TCP_IPV6_RECVPKTINFO;
10440 				/* Force it to be sent up with the next msg */
10441 				tcp->tcp_recvifindex = 0;
10442 				PASS_OPT_TO_IP(connp);
10443 			}
10444 			break;
10445 		case IPV6_RECVTCLASS:
10446 			if (!checkonly) {
10447 				if (onoff)
10448 					tcp->tcp_ipv6_recvancillary |=
10449 					    TCP_IPV6_RECVTCLASS;
10450 				else
10451 					tcp->tcp_ipv6_recvancillary &=
10452 					    ~TCP_IPV6_RECVTCLASS;
10453 				PASS_OPT_TO_IP(connp);
10454 			}
10455 			break;
10456 		case IPV6_RECVHOPLIMIT:
10457 			if (!checkonly) {
10458 				if (onoff)
10459 					tcp->tcp_ipv6_recvancillary |=
10460 					    TCP_IPV6_RECVHOPLIMIT;
10461 				else
10462 					tcp->tcp_ipv6_recvancillary &=
10463 					    ~TCP_IPV6_RECVHOPLIMIT;
10464 				/* Force it to be sent up with the next msg */
10465 				tcp->tcp_recvhops = 0xffffffffU;
10466 				PASS_OPT_TO_IP(connp);
10467 			}
10468 			break;
10469 		case IPV6_RECVHOPOPTS:
10470 			if (!checkonly) {
10471 				if (onoff)
10472 					tcp->tcp_ipv6_recvancillary |=
10473 					    TCP_IPV6_RECVHOPOPTS;
10474 				else
10475 					tcp->tcp_ipv6_recvancillary &=
10476 					    ~TCP_IPV6_RECVHOPOPTS;
10477 				PASS_OPT_TO_IP(connp);
10478 			}
10479 			break;
10480 		case IPV6_RECVDSTOPTS:
10481 			if (!checkonly) {
10482 				if (onoff)
10483 					tcp->tcp_ipv6_recvancillary |=
10484 					    TCP_IPV6_RECVDSTOPTS;
10485 				else
10486 					tcp->tcp_ipv6_recvancillary &=
10487 					    ~TCP_IPV6_RECVDSTOPTS;
10488 				PASS_OPT_TO_IP(connp);
10489 			}
10490 			break;
10491 		case _OLD_IPV6_RECVDSTOPTS:
10492 			if (!checkonly) {
10493 				if (onoff)
10494 					tcp->tcp_ipv6_recvancillary |=
10495 					    TCP_OLD_IPV6_RECVDSTOPTS;
10496 				else
10497 					tcp->tcp_ipv6_recvancillary &=
10498 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10499 			}
10500 			break;
10501 		case IPV6_RECVRTHDR:
10502 			if (!checkonly) {
10503 				if (onoff)
10504 					tcp->tcp_ipv6_recvancillary |=
10505 					    TCP_IPV6_RECVRTHDR;
10506 				else
10507 					tcp->tcp_ipv6_recvancillary &=
10508 					    ~TCP_IPV6_RECVRTHDR;
10509 				PASS_OPT_TO_IP(connp);
10510 			}
10511 			break;
10512 		case IPV6_RECVRTHDRDSTOPTS:
10513 			if (!checkonly) {
10514 				if (onoff)
10515 					tcp->tcp_ipv6_recvancillary |=
10516 					    TCP_IPV6_RECVRTDSTOPTS;
10517 				else
10518 					tcp->tcp_ipv6_recvancillary &=
10519 					    ~TCP_IPV6_RECVRTDSTOPTS;
10520 				PASS_OPT_TO_IP(connp);
10521 			}
10522 			break;
10523 		case IPV6_PKTINFO:
10524 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10525 				return (EINVAL);
10526 			if (checkonly)
10527 				break;
10528 
10529 			if (inlen == 0) {
10530 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10531 			} else {
10532 				struct in6_pktinfo *pkti;
10533 
10534 				pkti = (struct in6_pktinfo *)invalp;
10535 				/*
10536 				 * RFC 3542 states that ipi6_addr must be
10537 				 * the unspecified address when setting the
10538 				 * IPV6_PKTINFO sticky socket option on a
10539 				 * TCP socket.
10540 				 */
10541 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10542 					return (EINVAL);
10543 				/*
10544 				 * IP will validate the source address and
10545 				 * interface index.
10546 				 */
10547 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10548 					reterr = ip_set_options(tcp->tcp_connp,
10549 					    level, name, invalp, inlen, cr);
10550 				} else {
10551 					reterr = ip6_set_pktinfo(cr,
10552 					    tcp->tcp_connp, pkti);
10553 				}
10554 				if (reterr != 0)
10555 					return (reterr);
10556 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10557 				ipp->ipp_addr = pkti->ipi6_addr;
10558 				if (ipp->ipp_ifindex != 0)
10559 					ipp->ipp_fields |= IPPF_IFINDEX;
10560 				else
10561 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10562 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10563 					ipp->ipp_fields |= IPPF_ADDR;
10564 				else
10565 					ipp->ipp_fields &= ~IPPF_ADDR;
10566 			}
10567 			reterr = tcp_build_hdrs(tcp);
10568 			if (reterr != 0)
10569 				return (reterr);
10570 			break;
10571 		case IPV6_TCLASS:
10572 			if (inlen != 0 && inlen != sizeof (int))
10573 				return (EINVAL);
10574 			if (checkonly)
10575 				break;
10576 
10577 			if (inlen == 0) {
10578 				ipp->ipp_fields &= ~IPPF_TCLASS;
10579 			} else {
10580 				if (*i1 > 255 || *i1 < -1)
10581 					return (EINVAL);
10582 				if (*i1 == -1) {
10583 					ipp->ipp_tclass = 0;
10584 					*i1 = 0;
10585 				} else {
10586 					ipp->ipp_tclass = *i1;
10587 				}
10588 				ipp->ipp_fields |= IPPF_TCLASS;
10589 			}
10590 			reterr = tcp_build_hdrs(tcp);
10591 			if (reterr != 0)
10592 				return (reterr);
10593 			break;
10594 		case IPV6_NEXTHOP:
10595 			/*
10596 			 * IP will verify that the nexthop is reachable
10597 			 * and fail for sticky options.
10598 			 */
10599 			if (inlen != 0 && inlen != sizeof (sin6_t))
10600 				return (EINVAL);
10601 			if (checkonly)
10602 				break;
10603 
10604 			if (inlen == 0) {
10605 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10606 			} else {
10607 				sin6_t *sin6 = (sin6_t *)invalp;
10608 
10609 				if (sin6->sin6_family != AF_INET6)
10610 					return (EAFNOSUPPORT);
10611 				if (IN6_IS_ADDR_V4MAPPED(
10612 				    &sin6->sin6_addr))
10613 					return (EADDRNOTAVAIL);
10614 				ipp->ipp_nexthop = sin6->sin6_addr;
10615 				if (!IN6_IS_ADDR_UNSPECIFIED(
10616 				    &ipp->ipp_nexthop))
10617 					ipp->ipp_fields |= IPPF_NEXTHOP;
10618 				else
10619 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10620 			}
10621 			reterr = tcp_build_hdrs(tcp);
10622 			if (reterr != 0)
10623 				return (reterr);
10624 			PASS_OPT_TO_IP(connp);
10625 			break;
10626 		case IPV6_HOPOPTS: {
10627 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10628 
10629 			/*
10630 			 * Sanity checks - minimum size, size a multiple of
10631 			 * eight bytes, and matching size passed in.
10632 			 */
10633 			if (inlen != 0 &&
10634 			    inlen != (8 * (hopts->ip6h_len + 1)))
10635 				return (EINVAL);
10636 
10637 			if (checkonly)
10638 				break;
10639 
10640 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10641 			    (uchar_t **)&ipp->ipp_hopopts,
10642 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10643 			if (reterr != 0)
10644 				return (reterr);
10645 			if (ipp->ipp_hopoptslen == 0)
10646 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10647 			else
10648 				ipp->ipp_fields |= IPPF_HOPOPTS;
10649 			reterr = tcp_build_hdrs(tcp);
10650 			if (reterr != 0)
10651 				return (reterr);
10652 			break;
10653 		}
10654 		case IPV6_RTHDRDSTOPTS: {
10655 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10656 
10657 			/*
10658 			 * Sanity checks - minimum size, size a multiple of
10659 			 * eight bytes, and matching size passed in.
10660 			 */
10661 			if (inlen != 0 &&
10662 			    inlen != (8 * (dopts->ip6d_len + 1)))
10663 				return (EINVAL);
10664 
10665 			if (checkonly)
10666 				break;
10667 
10668 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10669 			    (uchar_t **)&ipp->ipp_rtdstopts,
10670 			    &ipp->ipp_rtdstoptslen, 0);
10671 			if (reterr != 0)
10672 				return (reterr);
10673 			if (ipp->ipp_rtdstoptslen == 0)
10674 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10675 			else
10676 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10677 			reterr = tcp_build_hdrs(tcp);
10678 			if (reterr != 0)
10679 				return (reterr);
10680 			break;
10681 		}
10682 		case IPV6_DSTOPTS: {
10683 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10684 
10685 			/*
10686 			 * Sanity checks - minimum size, size a multiple of
10687 			 * eight bytes, and matching size passed in.
10688 			 */
10689 			if (inlen != 0 &&
10690 			    inlen != (8 * (dopts->ip6d_len + 1)))
10691 				return (EINVAL);
10692 
10693 			if (checkonly)
10694 				break;
10695 
10696 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10697 			    (uchar_t **)&ipp->ipp_dstopts,
10698 			    &ipp->ipp_dstoptslen, 0);
10699 			if (reterr != 0)
10700 				return (reterr);
10701 			if (ipp->ipp_dstoptslen == 0)
10702 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10703 			else
10704 				ipp->ipp_fields |= IPPF_DSTOPTS;
10705 			reterr = tcp_build_hdrs(tcp);
10706 			if (reterr != 0)
10707 				return (reterr);
10708 			break;
10709 		}
10710 		case IPV6_RTHDR: {
10711 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10712 
10713 			/*
10714 			 * Sanity checks - minimum size, size a multiple of
10715 			 * eight bytes, and matching size passed in.
10716 			 */
10717 			if (inlen != 0 &&
10718 			    inlen != (8 * (rt->ip6r_len + 1)))
10719 				return (EINVAL);
10720 
10721 			if (checkonly)
10722 				break;
10723 
10724 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10725 			    (uchar_t **)&ipp->ipp_rthdr,
10726 			    &ipp->ipp_rthdrlen, 0);
10727 			if (reterr != 0)
10728 				return (reterr);
10729 			if (ipp->ipp_rthdrlen == 0)
10730 				ipp->ipp_fields &= ~IPPF_RTHDR;
10731 			else
10732 				ipp->ipp_fields |= IPPF_RTHDR;
10733 			reterr = tcp_build_hdrs(tcp);
10734 			if (reterr != 0)
10735 				return (reterr);
10736 			break;
10737 		}
10738 		case IPV6_V6ONLY:
10739 			if (!checkonly) {
10740 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10741 			}
10742 			break;
10743 		case IPV6_USE_MIN_MTU:
10744 			if (inlen != sizeof (int))
10745 				return (EINVAL);
10746 
10747 			if (*i1 < -1 || *i1 > 1)
10748 				return (EINVAL);
10749 
10750 			if (checkonly)
10751 				break;
10752 
10753 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10754 			ipp->ipp_use_min_mtu = *i1;
10755 			break;
10756 		case IPV6_SEC_OPT:
10757 			/*
10758 			 * We should not allow policy setting after
10759 			 * we start listening for connections.
10760 			 */
10761 			if (tcp->tcp_state == TCPS_LISTEN) {
10762 				return (EINVAL);
10763 			} else {
10764 				/* Handled at the IP level */
10765 				return (-EINVAL);
10766 			}
10767 		case IPV6_SRC_PREFERENCES:
10768 			if (inlen != sizeof (uint32_t))
10769 				return (EINVAL);
10770 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10771 			    *(uint32_t *)invalp);
10772 			if (reterr != 0) {
10773 				*outlenp = 0;
10774 				return (reterr);
10775 			}
10776 			break;
10777 		default:
10778 			*outlenp = 0;
10779 			return (EINVAL);
10780 		}
10781 		break;
10782 	}		/* end IPPROTO_IPV6 */
10783 	default:
10784 		*outlenp = 0;
10785 		return (EINVAL);
10786 	}
10787 	/*
10788 	 * Common case of OK return with outval same as inval
10789 	 */
10790 	if (invalp != outvalp) {
10791 		/* don't trust bcopy for identical src/dst */
10792 		(void) bcopy(invalp, outvalp, inlen);
10793 	}
10794 	*outlenp = inlen;
10795 	return (0);
10796 }
10797 
10798 /* ARGSUSED */
10799 int
10800 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10801     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10802     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10803 {
10804 	conn_t	*connp =  Q_TO_CONN(q);
10805 
10806 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10807 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10808 }
10809 
10810 int
10811 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10812     const void *optvalp, socklen_t optlen, cred_t *cr)
10813 {
10814 	conn_t		*connp = (conn_t *)proto_handle;
10815 	squeue_t	*sqp = connp->conn_sqp;
10816 	int		error;
10817 
10818 	ASSERT(connp->conn_upper_handle != NULL);
10819 	/*
10820 	 * Entering the squeue synchronously can result in a context switch,
10821 	 * which can cause a rather sever performance degradation. So we try to
10822 	 * handle whatever options we can without entering the squeue.
10823 	 */
10824 	if (level == IPPROTO_TCP) {
10825 		switch (option_name) {
10826 		case TCP_NODELAY:
10827 			if (optlen != sizeof (int32_t))
10828 				return (EINVAL);
10829 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10830 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10831 			    connp->conn_tcp->tcp_mss;
10832 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10833 			return (0);
10834 		default:
10835 			break;
10836 		}
10837 	}
10838 
10839 	error = squeue_synch_enter(sqp, connp, NULL);
10840 	if (error == ENOMEM) {
10841 		return (ENOMEM);
10842 	}
10843 
10844 	error = proto_opt_check(level, option_name, optlen, NULL,
10845 	    tcp_opt_obj.odb_opt_des_arr,
10846 	    tcp_opt_obj.odb_opt_arr_cnt,
10847 	    tcp_opt_obj.odb_topmost_tpiprovider,
10848 	    B_TRUE, B_FALSE, cr);
10849 
10850 	if (error != 0) {
10851 		if (error < 0) {
10852 			error = proto_tlitosyserr(-error);
10853 		}
10854 		squeue_synch_exit(sqp, connp);
10855 		return (error);
10856 	}
10857 
10858 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10859 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10860 	    NULL, cr, NULL);
10861 	squeue_synch_exit(sqp, connp);
10862 
10863 	if (error < 0) {
10864 		/*
10865 		 * Pass on to ip
10866 		 */
10867 		error = ip_set_options(connp, level, option_name, optvalp,
10868 		    optlen, cr);
10869 	}
10870 	return (error);
10871 }
10872 
10873 /*
10874  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10875  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10876  * headers, and the maximum size tcp header (to avoid reallocation
10877  * on the fly for additional tcp options).
10878  * Returns failure if can't allocate memory.
10879  */
10880 static int
10881 tcp_build_hdrs(tcp_t *tcp)
10882 {
10883 	char	*hdrs;
10884 	uint_t	hdrs_len;
10885 	ip6i_t	*ip6i;
10886 	char	buf[TCP_MAX_HDR_LENGTH];
10887 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10888 	in6_addr_t src, dst;
10889 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10890 	conn_t *connp = tcp->tcp_connp;
10891 
10892 	/*
10893 	 * save the existing tcp header and source/dest IP addresses
10894 	 */
10895 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10896 	src = tcp->tcp_ip6h->ip6_src;
10897 	dst = tcp->tcp_ip6h->ip6_dst;
10898 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10899 	ASSERT(hdrs_len != 0);
10900 	if (hdrs_len > tcp->tcp_iphc_len) {
10901 		/* Need to reallocate */
10902 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10903 		if (hdrs == NULL)
10904 			return (ENOMEM);
10905 		if (tcp->tcp_iphc != NULL) {
10906 			if (tcp->tcp_hdr_grown) {
10907 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10908 			} else {
10909 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10910 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10911 			}
10912 			tcp->tcp_iphc_len = 0;
10913 		}
10914 		ASSERT(tcp->tcp_iphc_len == 0);
10915 		tcp->tcp_iphc = hdrs;
10916 		tcp->tcp_iphc_len = hdrs_len;
10917 		tcp->tcp_hdr_grown = B_TRUE;
10918 	}
10919 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10920 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10921 
10922 	/* Set header fields not in ipp */
10923 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10924 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10925 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10926 	} else {
10927 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10928 	}
10929 	/*
10930 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10931 	 *
10932 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10933 	 */
10934 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10935 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10936 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10937 
10938 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10939 
10940 	tcp->tcp_ip6h->ip6_src = src;
10941 	tcp->tcp_ip6h->ip6_dst = dst;
10942 
10943 	/*
10944 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10945 	 * the default value for TCP.
10946 	 */
10947 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10948 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10949 
10950 	/*
10951 	 * If we're setting extension headers after a connection
10952 	 * has been established, and if we have a routing header
10953 	 * among the extension headers, call ip_massage_options_v6 to
10954 	 * manipulate the routing header/ip6_dst set the checksum
10955 	 * difference in the tcp header template.
10956 	 * (This happens in tcp_connect_ipv6 if the routing header
10957 	 * is set prior to the connect.)
10958 	 * Set the tcp_sum to zero first in case we've cleared a
10959 	 * routing header or don't have one at all.
10960 	 */
10961 	tcp->tcp_sum = 0;
10962 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10963 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10964 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10965 		    (uint8_t *)tcp->tcp_tcph);
10966 		if (rth != NULL) {
10967 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10968 			    rth, tcps->tcps_netstack);
10969 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10970 			    (tcp->tcp_sum >> 16));
10971 		}
10972 	}
10973 
10974 	/* Try to get everything in a single mblk */
10975 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10976 	    hdrs_len + tcps->tcps_wroff_xtra);
10977 	return (0);
10978 }
10979 
10980 /*
10981  * Transfer any source route option from ipha to buf/dst in reversed form.
10982  */
10983 static int
10984 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10985 {
10986 	ipoptp_t	opts;
10987 	uchar_t		*opt;
10988 	uint8_t		optval;
10989 	uint8_t		optlen;
10990 	uint32_t	len = 0;
10991 
10992 	for (optval = ipoptp_first(&opts, ipha);
10993 	    optval != IPOPT_EOL;
10994 	    optval = ipoptp_next(&opts)) {
10995 		opt = opts.ipoptp_cur;
10996 		optlen = opts.ipoptp_len;
10997 		switch (optval) {
10998 			int	off1, off2;
10999 		case IPOPT_SSRR:
11000 		case IPOPT_LSRR:
11001 
11002 			/* Reverse source route */
11003 			/*
11004 			 * First entry should be the next to last one in the
11005 			 * current source route (the last entry is our
11006 			 * address.)
11007 			 * The last entry should be the final destination.
11008 			 */
11009 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11010 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11011 			off1 = IPOPT_MINOFF_SR - 1;
11012 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11013 			if (off2 < 0) {
11014 				/* No entries in source route */
11015 				break;
11016 			}
11017 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11018 			/*
11019 			 * Note: use src since ipha has not had its src
11020 			 * and dst reversed (it is in the state it was
11021 			 * received.
11022 			 */
11023 			bcopy(&ipha->ipha_src, buf + off2,
11024 			    IP_ADDR_LEN);
11025 			off2 -= IP_ADDR_LEN;
11026 
11027 			while (off2 > 0) {
11028 				bcopy(opt + off2, buf + off1,
11029 				    IP_ADDR_LEN);
11030 				off1 += IP_ADDR_LEN;
11031 				off2 -= IP_ADDR_LEN;
11032 			}
11033 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11034 			buf += optlen;
11035 			len += optlen;
11036 			break;
11037 		}
11038 	}
11039 done:
11040 	/* Pad the resulting options */
11041 	while (len & 0x3) {
11042 		*buf++ = IPOPT_EOL;
11043 		len++;
11044 	}
11045 	return (len);
11046 }
11047 
11048 
11049 /*
11050  * Extract and revert a source route from ipha (if any)
11051  * and then update the relevant fields in both tcp_t and the standard header.
11052  */
11053 static void
11054 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11055 {
11056 	char	buf[TCP_MAX_HDR_LENGTH];
11057 	uint_t	tcph_len;
11058 	int	len;
11059 
11060 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11061 	len = IPH_HDR_LENGTH(ipha);
11062 	if (len == IP_SIMPLE_HDR_LENGTH)
11063 		/* Nothing to do */
11064 		return;
11065 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11066 	    (len & 0x3))
11067 		return;
11068 
11069 	tcph_len = tcp->tcp_tcp_hdr_len;
11070 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11071 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11072 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11073 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11074 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11075 	len += IP_SIMPLE_HDR_LENGTH;
11076 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11077 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11078 	if ((int)tcp->tcp_sum < 0)
11079 		tcp->tcp_sum--;
11080 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11081 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11082 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11083 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11084 	tcp->tcp_ip_hdr_len = len;
11085 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11086 	    (IP_VERSION << 4) | (len >> 2);
11087 	len += tcph_len;
11088 	tcp->tcp_hdr_len = len;
11089 }
11090 
11091 /*
11092  * Copy the standard header into its new location,
11093  * lay in the new options and then update the relevant
11094  * fields in both tcp_t and the standard header.
11095  */
11096 static int
11097 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11098 {
11099 	uint_t	tcph_len;
11100 	uint8_t	*ip_optp;
11101 	tcph_t	*new_tcph;
11102 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11103 	conn_t	*connp = tcp->tcp_connp;
11104 
11105 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11106 		return (EINVAL);
11107 
11108 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11109 		return (EINVAL);
11110 
11111 	if (checkonly) {
11112 		/*
11113 		 * do not really set, just pretend to - T_CHECK
11114 		 */
11115 		return (0);
11116 	}
11117 
11118 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11119 	if (tcp->tcp_label_len > 0) {
11120 		int padlen;
11121 		uint8_t opt;
11122 
11123 		/* convert list termination to no-ops */
11124 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11125 		ip_optp += ip_optp[IPOPT_OLEN];
11126 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11127 		while (--padlen >= 0)
11128 			*ip_optp++ = opt;
11129 	}
11130 	tcph_len = tcp->tcp_tcp_hdr_len;
11131 	new_tcph = (tcph_t *)(ip_optp + len);
11132 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11133 	tcp->tcp_tcph = new_tcph;
11134 	bcopy(ptr, ip_optp, len);
11135 
11136 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11137 
11138 	tcp->tcp_ip_hdr_len = len;
11139 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11140 	    (IP_VERSION << 4) | (len >> 2);
11141 	tcp->tcp_hdr_len = len + tcph_len;
11142 	if (!TCP_IS_DETACHED(tcp)) {
11143 		/* Always allocate room for all options. */
11144 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11145 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11146 	}
11147 	return (0);
11148 }
11149 
11150 /* Get callback routine passed to nd_load by tcp_param_register */
11151 /* ARGSUSED */
11152 static int
11153 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11154 {
11155 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11156 
11157 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11158 	return (0);
11159 }
11160 
11161 /*
11162  * Walk through the param array specified registering each element with the
11163  * named dispatch handler.
11164  */
11165 static boolean_t
11166 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11167 {
11168 	for (; cnt-- > 0; tcppa++) {
11169 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11170 			if (!nd_load(ndp, tcppa->tcp_param_name,
11171 			    tcp_param_get, tcp_param_set,
11172 			    (caddr_t)tcppa)) {
11173 				nd_free(ndp);
11174 				return (B_FALSE);
11175 			}
11176 		}
11177 	}
11178 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11179 	    KM_SLEEP);
11180 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11181 	    sizeof (tcpparam_t));
11182 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11183 	    tcp_param_get, tcp_param_set_aligned,
11184 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11185 		nd_free(ndp);
11186 		return (B_FALSE);
11187 	}
11188 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11189 	    KM_SLEEP);
11190 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11191 	    sizeof (tcpparam_t));
11192 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11193 	    tcp_param_get, tcp_param_set_aligned,
11194 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11195 		nd_free(ndp);
11196 		return (B_FALSE);
11197 	}
11198 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11199 	    KM_SLEEP);
11200 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11201 	    sizeof (tcpparam_t));
11202 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11203 	    tcp_param_get, tcp_param_set_aligned,
11204 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11205 		nd_free(ndp);
11206 		return (B_FALSE);
11207 	}
11208 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11209 	    KM_SLEEP);
11210 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11211 	    sizeof (tcpparam_t));
11212 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11213 	    tcp_param_get, tcp_param_set_aligned,
11214 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11215 		nd_free(ndp);
11216 		return (B_FALSE);
11217 	}
11218 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11219 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11220 		nd_free(ndp);
11221 		return (B_FALSE);
11222 	}
11223 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11224 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11225 		nd_free(ndp);
11226 		return (B_FALSE);
11227 	}
11228 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11229 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11230 		nd_free(ndp);
11231 		return (B_FALSE);
11232 	}
11233 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11234 	    tcp_1948_phrase_set, NULL)) {
11235 		nd_free(ndp);
11236 		return (B_FALSE);
11237 	}
11238 	/*
11239 	 * Dummy ndd variables - only to convey obsolescence information
11240 	 * through printing of their name (no get or set routines)
11241 	 * XXX Remove in future releases ?
11242 	 */
11243 	if (!nd_load(ndp,
11244 	    "tcp_close_wait_interval(obsoleted - "
11245 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11246 		nd_free(ndp);
11247 		return (B_FALSE);
11248 	}
11249 	return (B_TRUE);
11250 }
11251 
11252 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11253 /* ARGSUSED */
11254 static int
11255 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11256     cred_t *cr)
11257 {
11258 	long new_value;
11259 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11260 
11261 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11262 	    new_value < tcppa->tcp_param_min ||
11263 	    new_value > tcppa->tcp_param_max) {
11264 		return (EINVAL);
11265 	}
11266 	/*
11267 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11268 	 * round it up.  For future 64 bit requirement, we actually make it
11269 	 * a multiple of 8.
11270 	 */
11271 	if (new_value & 0x7) {
11272 		new_value = (new_value & ~0x7) + 0x8;
11273 	}
11274 	tcppa->tcp_param_val = new_value;
11275 	return (0);
11276 }
11277 
11278 /* Set callback routine passed to nd_load by tcp_param_register */
11279 /* ARGSUSED */
11280 static int
11281 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11282 {
11283 	long	new_value;
11284 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11285 
11286 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11287 	    new_value < tcppa->tcp_param_min ||
11288 	    new_value > tcppa->tcp_param_max) {
11289 		return (EINVAL);
11290 	}
11291 	tcppa->tcp_param_val = new_value;
11292 	return (0);
11293 }
11294 
11295 /*
11296  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11297  * is filled, return as much as we can.  The message passed in may be
11298  * multi-part, chained using b_cont.  "start" is the starting sequence
11299  * number for this piece.
11300  */
11301 static mblk_t *
11302 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11303 {
11304 	uint32_t	end;
11305 	mblk_t		*mp1;
11306 	mblk_t		*mp2;
11307 	mblk_t		*next_mp;
11308 	uint32_t	u1;
11309 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11310 
11311 	/* Walk through all the new pieces. */
11312 	do {
11313 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11314 		    (uintptr_t)INT_MAX);
11315 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11316 		next_mp = mp->b_cont;
11317 		if (start == end) {
11318 			/* Empty.  Blast it. */
11319 			freeb(mp);
11320 			continue;
11321 		}
11322 		mp->b_cont = NULL;
11323 		TCP_REASS_SET_SEQ(mp, start);
11324 		TCP_REASS_SET_END(mp, end);
11325 		mp1 = tcp->tcp_reass_tail;
11326 		if (!mp1) {
11327 			tcp->tcp_reass_tail = mp;
11328 			tcp->tcp_reass_head = mp;
11329 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11330 			UPDATE_MIB(&tcps->tcps_mib,
11331 			    tcpInDataUnorderBytes, end - start);
11332 			continue;
11333 		}
11334 		/* New stuff completely beyond tail? */
11335 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11336 			/* Link it on end. */
11337 			mp1->b_cont = mp;
11338 			tcp->tcp_reass_tail = mp;
11339 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11340 			UPDATE_MIB(&tcps->tcps_mib,
11341 			    tcpInDataUnorderBytes, end - start);
11342 			continue;
11343 		}
11344 		mp1 = tcp->tcp_reass_head;
11345 		u1 = TCP_REASS_SEQ(mp1);
11346 		/* New stuff at the front? */
11347 		if (SEQ_LT(start, u1)) {
11348 			/* Yes... Check for overlap. */
11349 			mp->b_cont = mp1;
11350 			tcp->tcp_reass_head = mp;
11351 			tcp_reass_elim_overlap(tcp, mp);
11352 			continue;
11353 		}
11354 		/*
11355 		 * The new piece fits somewhere between the head and tail.
11356 		 * We find our slot, where mp1 precedes us and mp2 trails.
11357 		 */
11358 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11359 			u1 = TCP_REASS_SEQ(mp2);
11360 			if (SEQ_LEQ(start, u1))
11361 				break;
11362 		}
11363 		/* Link ourselves in */
11364 		mp->b_cont = mp2;
11365 		mp1->b_cont = mp;
11366 
11367 		/* Trim overlap with following mblk(s) first */
11368 		tcp_reass_elim_overlap(tcp, mp);
11369 
11370 		/* Trim overlap with preceding mblk */
11371 		tcp_reass_elim_overlap(tcp, mp1);
11372 
11373 	} while (start = end, mp = next_mp);
11374 	mp1 = tcp->tcp_reass_head;
11375 	/* Anything ready to go? */
11376 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11377 		return (NULL);
11378 	/* Eat what we can off the queue */
11379 	for (;;) {
11380 		mp = mp1->b_cont;
11381 		end = TCP_REASS_END(mp1);
11382 		TCP_REASS_SET_SEQ(mp1, 0);
11383 		TCP_REASS_SET_END(mp1, 0);
11384 		if (!mp) {
11385 			tcp->tcp_reass_tail = NULL;
11386 			break;
11387 		}
11388 		if (end != TCP_REASS_SEQ(mp)) {
11389 			mp1->b_cont = NULL;
11390 			break;
11391 		}
11392 		mp1 = mp;
11393 	}
11394 	mp1 = tcp->tcp_reass_head;
11395 	tcp->tcp_reass_head = mp;
11396 	return (mp1);
11397 }
11398 
11399 /* Eliminate any overlap that mp may have over later mblks */
11400 static void
11401 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11402 {
11403 	uint32_t	end;
11404 	mblk_t		*mp1;
11405 	uint32_t	u1;
11406 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11407 
11408 	end = TCP_REASS_END(mp);
11409 	while ((mp1 = mp->b_cont) != NULL) {
11410 		u1 = TCP_REASS_SEQ(mp1);
11411 		if (!SEQ_GT(end, u1))
11412 			break;
11413 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11414 			mp->b_wptr -= end - u1;
11415 			TCP_REASS_SET_END(mp, u1);
11416 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11417 			UPDATE_MIB(&tcps->tcps_mib,
11418 			    tcpInDataPartDupBytes, end - u1);
11419 			break;
11420 		}
11421 		mp->b_cont = mp1->b_cont;
11422 		TCP_REASS_SET_SEQ(mp1, 0);
11423 		TCP_REASS_SET_END(mp1, 0);
11424 		freeb(mp1);
11425 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11426 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11427 	}
11428 	if (!mp1)
11429 		tcp->tcp_reass_tail = mp;
11430 }
11431 
11432 static uint_t
11433 tcp_rwnd_reopen(tcp_t *tcp)
11434 {
11435 	uint_t ret = 0;
11436 	uint_t thwin;
11437 
11438 	/* Learn the latest rwnd information that we sent to the other side. */
11439 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11440 	    << tcp->tcp_rcv_ws;
11441 	/* This is peer's calculated send window (our receive window). */
11442 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11443 	/*
11444 	 * Increase the receive window to max.  But we need to do receiver
11445 	 * SWS avoidance.  This means that we need to check the increase of
11446 	 * of receive window is at least 1 MSS.
11447 	 */
11448 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11449 		/*
11450 		 * If the window that the other side knows is less than max
11451 		 * deferred acks segments, send an update immediately.
11452 		 */
11453 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11454 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11455 			ret = TH_ACK_NEEDED;
11456 		}
11457 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11458 	}
11459 	return (ret);
11460 }
11461 
11462 /*
11463  * Send up all messages queued on tcp_rcv_list.
11464  */
11465 static uint_t
11466 tcp_rcv_drain(tcp_t *tcp)
11467 {
11468 	mblk_t *mp;
11469 	uint_t ret = 0;
11470 #ifdef DEBUG
11471 	uint_t cnt = 0;
11472 #endif
11473 	queue_t	*q = tcp->tcp_rq;
11474 
11475 	/* Can't drain on an eager connection */
11476 	if (tcp->tcp_listener != NULL)
11477 		return (ret);
11478 
11479 	/* Can't be a non-STREAMS connection */
11480 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
11481 
11482 	/* No need for the push timer now. */
11483 	if (tcp->tcp_push_tid != 0) {
11484 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11485 		tcp->tcp_push_tid = 0;
11486 	}
11487 
11488 	/*
11489 	 * Handle two cases here: we are currently fused or we were
11490 	 * previously fused and have some urgent data to be delivered
11491 	 * upstream.  The latter happens because we either ran out of
11492 	 * memory or were detached and therefore sending the SIGURG was
11493 	 * deferred until this point.  In either case we pass control
11494 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11495 	 * some work.
11496 	 */
11497 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11498 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11499 		    tcp->tcp_fused_sigurg_mp != NULL);
11500 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11501 		    &tcp->tcp_fused_sigurg_mp))
11502 			return (ret);
11503 	}
11504 
11505 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11506 		tcp->tcp_rcv_list = mp->b_next;
11507 		mp->b_next = NULL;
11508 #ifdef DEBUG
11509 		cnt += msgdsize(mp);
11510 #endif
11511 		/* Does this need SSL processing first? */
11512 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11513 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11514 			    mblk_t *, mp);
11515 			tcp_kssl_input(tcp, mp);
11516 			continue;
11517 		}
11518 		putnext(q, mp);
11519 	}
11520 #ifdef DEBUG
11521 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11522 #endif
11523 	tcp->tcp_rcv_last_head = NULL;
11524 	tcp->tcp_rcv_last_tail = NULL;
11525 	tcp->tcp_rcv_cnt = 0;
11526 
11527 	if (canputnext(q))
11528 		return (tcp_rwnd_reopen(tcp));
11529 
11530 	return (ret);
11531 }
11532 
11533 /*
11534  * Queue data on tcp_rcv_list which is a b_next chain.
11535  * tcp_rcv_last_head/tail is the last element of this chain.
11536  * Each element of the chain is a b_cont chain.
11537  *
11538  * M_DATA messages are added to the current element.
11539  * Other messages are added as new (b_next) elements.
11540  */
11541 void
11542 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11543 {
11544 	ASSERT(seg_len == msgdsize(mp));
11545 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11546 
11547 	if (tcp->tcp_rcv_list == NULL) {
11548 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11549 		tcp->tcp_rcv_list = mp;
11550 		tcp->tcp_rcv_last_head = mp;
11551 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11552 		tcp->tcp_rcv_last_tail->b_cont = mp;
11553 	} else {
11554 		tcp->tcp_rcv_last_head->b_next = mp;
11555 		tcp->tcp_rcv_last_head = mp;
11556 	}
11557 
11558 	while (mp->b_cont)
11559 		mp = mp->b_cont;
11560 
11561 	tcp->tcp_rcv_last_tail = mp;
11562 	tcp->tcp_rcv_cnt += seg_len;
11563 	tcp->tcp_rwnd -= seg_len;
11564 }
11565 
11566 /*
11567  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11568  *
11569  * This is the default entry function into TCP on the read side. TCP is
11570  * always entered via squeue i.e. using squeue's for mutual exclusion.
11571  * When classifier does a lookup to find the tcp, it also puts a reference
11572  * on the conn structure associated so the tcp is guaranteed to exist
11573  * when we come here. We still need to check the state because it might
11574  * as well has been closed. The squeue processing function i.e. squeue_enter,
11575  * is responsible for doing the CONN_DEC_REF.
11576  *
11577  * Apart from the default entry point, IP also sends packets directly to
11578  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11579  * connections.
11580  */
11581 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11582 void
11583 tcp_input(void *arg, mblk_t *mp, void *arg2)
11584 {
11585 	conn_t	*connp = (conn_t *)arg;
11586 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11587 
11588 	/* arg2 is the sqp */
11589 	ASSERT(arg2 != NULL);
11590 	ASSERT(mp != NULL);
11591 
11592 	/*
11593 	 * Don't accept any input on a closed tcp as this TCP logically does
11594 	 * not exist on the system. Don't proceed further with this TCP.
11595 	 * For eg. this packet could trigger another close of this tcp
11596 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11597 	 * tcp_clean_death / tcp_closei_local must be called at most once
11598 	 * on a TCP. In this case we need to refeed the packet into the
11599 	 * classifier and figure out where the packet should go. Need to
11600 	 * preserve the recv_ill somehow. Until we figure that out, for
11601 	 * now just drop the packet if we can't classify the packet.
11602 	 */
11603 	if (tcp->tcp_state == TCPS_CLOSED ||
11604 	    tcp->tcp_state == TCPS_BOUND) {
11605 		conn_t	*new_connp;
11606 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11607 
11608 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11609 		if (new_connp != NULL) {
11610 			tcp_reinput(new_connp, mp, arg2);
11611 			return;
11612 		}
11613 		/* We failed to classify. For now just drop the packet */
11614 		freemsg(mp);
11615 		return;
11616 	}
11617 
11618 	if (DB_TYPE(mp) != M_DATA) {
11619 		tcp_rput_common(tcp, mp);
11620 		return;
11621 	}
11622 
11623 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11624 		squeue_t	*final_sqp;
11625 
11626 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11627 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11628 		DB_CKSUMSTART(mp) = 0;
11629 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11630 		    connp->conn_final_sqp == NULL &&
11631 		    tcp_outbound_squeue_switch) {
11632 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11633 			connp->conn_final_sqp = final_sqp;
11634 			if (connp->conn_final_sqp != connp->conn_sqp) {
11635 				CONN_INC_REF(connp);
11636 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11637 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11638 				    tcp_rput_data, connp, ip_squeue_flag,
11639 				    SQTAG_CONNECT_FINISH);
11640 				return;
11641 			}
11642 		}
11643 	}
11644 	tcp_rput_data(connp, mp, arg2);
11645 }
11646 
11647 /*
11648  * The read side put procedure.
11649  * The packets passed up by ip are assume to be aligned according to
11650  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11651  */
11652 static void
11653 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11654 {
11655 	/*
11656 	 * tcp_rput_data() does not expect M_CTL except for the case
11657 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11658 	 * type. Need to make sure that any other M_CTLs don't make
11659 	 * it to tcp_rput_data since it is not expecting any and doesn't
11660 	 * check for it.
11661 	 */
11662 	if (DB_TYPE(mp) == M_CTL) {
11663 		switch (*(uint32_t *)(mp->b_rptr)) {
11664 		case TCP_IOC_ABORT_CONN:
11665 			/*
11666 			 * Handle connection abort request.
11667 			 */
11668 			tcp_ioctl_abort_handler(tcp, mp);
11669 			return;
11670 		case IPSEC_IN:
11671 			/*
11672 			 * Only secure icmp arrive in TCP and they
11673 			 * don't go through data path.
11674 			 */
11675 			tcp_icmp_error(tcp, mp);
11676 			return;
11677 		case IN_PKTINFO:
11678 			/*
11679 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11680 			 * sockets that are receiving IPv4 traffic. tcp
11681 			 */
11682 			ASSERT(tcp->tcp_family == AF_INET6);
11683 			ASSERT(tcp->tcp_ipv6_recvancillary &
11684 			    TCP_IPV6_RECVPKTINFO);
11685 			tcp_rput_data(tcp->tcp_connp, mp,
11686 			    tcp->tcp_connp->conn_sqp);
11687 			return;
11688 		case MDT_IOC_INFO_UPDATE:
11689 			/*
11690 			 * Handle Multidata information update; the
11691 			 * following routine will free the message.
11692 			 */
11693 			if (tcp->tcp_connp->conn_mdt_ok) {
11694 				tcp_mdt_update(tcp,
11695 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11696 				    B_FALSE);
11697 			}
11698 			freemsg(mp);
11699 			return;
11700 		case LSO_IOC_INFO_UPDATE:
11701 			/*
11702 			 * Handle LSO information update; the following
11703 			 * routine will free the message.
11704 			 */
11705 			if (tcp->tcp_connp->conn_lso_ok) {
11706 				tcp_lso_update(tcp,
11707 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11708 			}
11709 			freemsg(mp);
11710 			return;
11711 		default:
11712 			/*
11713 			 * tcp_icmp_err() will process the M_CTL packets.
11714 			 * Non-ICMP packets, if any, will be discarded in
11715 			 * tcp_icmp_err(). We will process the ICMP packet
11716 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11717 			 * incoming ICMP packet may result in changing
11718 			 * the tcp_mss, which we would need if we have
11719 			 * packets to retransmit.
11720 			 */
11721 			tcp_icmp_error(tcp, mp);
11722 			return;
11723 		}
11724 	}
11725 
11726 	/* No point processing the message if tcp is already closed */
11727 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11728 		freemsg(mp);
11729 		return;
11730 	}
11731 
11732 	tcp_rput_other(tcp, mp);
11733 }
11734 
11735 
11736 /* The minimum of smoothed mean deviation in RTO calculation. */
11737 #define	TCP_SD_MIN	400
11738 
11739 /*
11740  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11741  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11742  * are the same as those in Appendix A.2 of that paper.
11743  *
11744  * m = new measurement
11745  * sa = smoothed RTT average (8 * average estimates).
11746  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11747  */
11748 static void
11749 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11750 {
11751 	long m = TICK_TO_MSEC(rtt);
11752 	clock_t sa = tcp->tcp_rtt_sa;
11753 	clock_t sv = tcp->tcp_rtt_sd;
11754 	clock_t rto;
11755 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11756 
11757 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11758 	tcp->tcp_rtt_update++;
11759 
11760 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11761 	if (sa != 0) {
11762 		/*
11763 		 * Update average estimator:
11764 		 *	new rtt = 7/8 old rtt + 1/8 Error
11765 		 */
11766 
11767 		/* m is now Error in estimate. */
11768 		m -= sa >> 3;
11769 		if ((sa += m) <= 0) {
11770 			/*
11771 			 * Don't allow the smoothed average to be negative.
11772 			 * We use 0 to denote reinitialization of the
11773 			 * variables.
11774 			 */
11775 			sa = 1;
11776 		}
11777 
11778 		/*
11779 		 * Update deviation estimator:
11780 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11781 		 */
11782 		if (m < 0)
11783 			m = -m;
11784 		m -= sv >> 2;
11785 		sv += m;
11786 	} else {
11787 		/*
11788 		 * This follows BSD's implementation.  So the reinitialized
11789 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11790 		 * link is bandwidth dominated, doubling the window size
11791 		 * during slow start means doubling the RTT.  We want to be
11792 		 * more conservative when we reinitialize our estimates.  3
11793 		 * is just a convenient number.
11794 		 */
11795 		sa = m << 3;
11796 		sv = m << 1;
11797 	}
11798 	if (sv < TCP_SD_MIN) {
11799 		/*
11800 		 * We do not know that if sa captures the delay ACK
11801 		 * effect as in a long train of segments, a receiver
11802 		 * does not delay its ACKs.  So set the minimum of sv
11803 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11804 		 * of BSD DATO.  That means the minimum of mean
11805 		 * deviation is 100 ms.
11806 		 *
11807 		 */
11808 		sv = TCP_SD_MIN;
11809 	}
11810 	tcp->tcp_rtt_sa = sa;
11811 	tcp->tcp_rtt_sd = sv;
11812 	/*
11813 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11814 	 *
11815 	 * Add tcp_rexmit_interval extra in case of extreme environment
11816 	 * where the algorithm fails to work.  The default value of
11817 	 * tcp_rexmit_interval_extra should be 0.
11818 	 *
11819 	 * As we use a finer grained clock than BSD and update
11820 	 * RTO for every ACKs, add in another .25 of RTT to the
11821 	 * deviation of RTO to accomodate burstiness of 1/4 of
11822 	 * window size.
11823 	 */
11824 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11825 
11826 	if (rto > tcps->tcps_rexmit_interval_max) {
11827 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11828 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11829 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11830 	} else {
11831 		tcp->tcp_rto = rto;
11832 	}
11833 
11834 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11835 	tcp->tcp_timer_backoff = 0;
11836 }
11837 
11838 /*
11839  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11840  * send queue which starts at the given sequence number. If the given
11841  * sequence number is equal to last valid sequence number (tcp_snxt), the
11842  * returned mblk is the last valid mblk, and off is set to the length of
11843  * that mblk.
11844  *
11845  * send queue which starts at the given seq. no.
11846  *
11847  * Parameters:
11848  *	tcp_t *tcp: the tcp instance pointer.
11849  *	uint32_t seq: the starting seq. no of the requested segment.
11850  *	int32_t *off: after the execution, *off will be the offset to
11851  *		the returned mblk which points to the requested seq no.
11852  *		It is the caller's responsibility to send in a non-null off.
11853  *
11854  * Return:
11855  *	A mblk_t pointer pointing to the requested segment in send queue.
11856  */
11857 static mblk_t *
11858 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11859 {
11860 	int32_t	cnt;
11861 	mblk_t	*mp;
11862 
11863 	/* Defensive coding.  Make sure we don't send incorrect data. */
11864 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
11865 		return (NULL);
11866 
11867 	cnt = seq - tcp->tcp_suna;
11868 	mp = tcp->tcp_xmit_head;
11869 	while (cnt > 0 && mp != NULL) {
11870 		cnt -= mp->b_wptr - mp->b_rptr;
11871 		if (cnt <= 0) {
11872 			cnt += mp->b_wptr - mp->b_rptr;
11873 			break;
11874 		}
11875 		mp = mp->b_cont;
11876 	}
11877 	ASSERT(mp != NULL);
11878 	*off = cnt;
11879 	return (mp);
11880 }
11881 
11882 /*
11883  * This function handles all retransmissions if SACK is enabled for this
11884  * connection.  First it calculates how many segments can be retransmitted
11885  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11886  * segments.  A segment is eligible if sack_cnt for that segment is greater
11887  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11888  * all eligible segments, it checks to see if TCP can send some new segments
11889  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11890  *
11891  * Parameters:
11892  *	tcp_t *tcp: the tcp structure of the connection.
11893  *	uint_t *flags: in return, appropriate value will be set for
11894  *	tcp_rput_data().
11895  */
11896 static void
11897 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11898 {
11899 	notsack_blk_t	*notsack_blk;
11900 	int32_t		usable_swnd;
11901 	int32_t		mss;
11902 	uint32_t	seg_len;
11903 	mblk_t		*xmit_mp;
11904 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11905 
11906 	ASSERT(tcp->tcp_sack_info != NULL);
11907 	ASSERT(tcp->tcp_notsack_list != NULL);
11908 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11909 
11910 	/* Defensive coding in case there is a bug... */
11911 	if (tcp->tcp_notsack_list == NULL) {
11912 		return;
11913 	}
11914 	notsack_blk = tcp->tcp_notsack_list;
11915 	mss = tcp->tcp_mss;
11916 
11917 	/*
11918 	 * Limit the num of outstanding data in the network to be
11919 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11920 	 */
11921 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11922 
11923 	/* At least retransmit 1 MSS of data. */
11924 	if (usable_swnd <= 0) {
11925 		usable_swnd = mss;
11926 	}
11927 
11928 	/* Make sure no new RTT samples will be taken. */
11929 	tcp->tcp_csuna = tcp->tcp_snxt;
11930 
11931 	notsack_blk = tcp->tcp_notsack_list;
11932 	while (usable_swnd > 0) {
11933 		mblk_t		*snxt_mp, *tmp_mp;
11934 		tcp_seq		begin = tcp->tcp_sack_snxt;
11935 		tcp_seq		end;
11936 		int32_t		off;
11937 
11938 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11939 			if (SEQ_GT(notsack_blk->end, begin) &&
11940 			    (notsack_blk->sack_cnt >=
11941 			    tcps->tcps_dupack_fast_retransmit)) {
11942 				end = notsack_blk->end;
11943 				if (SEQ_LT(begin, notsack_blk->begin)) {
11944 					begin = notsack_blk->begin;
11945 				}
11946 				break;
11947 			}
11948 		}
11949 		/*
11950 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11951 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11952 		 * set to tcp_cwnd_ssthresh.
11953 		 */
11954 		if (notsack_blk == NULL) {
11955 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11956 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11957 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11958 				ASSERT(tcp->tcp_cwnd > 0);
11959 				return;
11960 			} else {
11961 				usable_swnd = usable_swnd / mss;
11962 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11963 				    MAX(usable_swnd * mss, mss);
11964 				*flags |= TH_XMIT_NEEDED;
11965 				return;
11966 			}
11967 		}
11968 
11969 		/*
11970 		 * Note that we may send more than usable_swnd allows here
11971 		 * because of round off, but no more than 1 MSS of data.
11972 		 */
11973 		seg_len = end - begin;
11974 		if (seg_len > mss)
11975 			seg_len = mss;
11976 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11977 		ASSERT(snxt_mp != NULL);
11978 		/* This should not happen.  Defensive coding again... */
11979 		if (snxt_mp == NULL) {
11980 			return;
11981 		}
11982 
11983 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11984 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11985 		if (xmit_mp == NULL)
11986 			return;
11987 
11988 		usable_swnd -= seg_len;
11989 		tcp->tcp_pipe += seg_len;
11990 		tcp->tcp_sack_snxt = begin + seg_len;
11991 
11992 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11993 
11994 		/*
11995 		 * Update the send timestamp to avoid false retransmission.
11996 		 */
11997 		snxt_mp->b_prev = (mblk_t *)lbolt;
11998 
11999 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12000 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12001 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12002 		/*
12003 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12004 		 * This happens when new data sent during fast recovery is
12005 		 * also lost.  If TCP retransmits those new data, it needs
12006 		 * to extend SACK recover phase to avoid starting another
12007 		 * fast retransmit/recovery unnecessarily.
12008 		 */
12009 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12010 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12011 		}
12012 	}
12013 }
12014 
12015 /*
12016  * This function handles policy checking at TCP level for non-hard_bound/
12017  * detached connections.
12018  */
12019 static boolean_t
12020 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12021     boolean_t secure, boolean_t mctl_present)
12022 {
12023 	ipsec_latch_t *ipl = NULL;
12024 	ipsec_action_t *act = NULL;
12025 	mblk_t *data_mp;
12026 	ipsec_in_t *ii;
12027 	const char *reason;
12028 	kstat_named_t *counter;
12029 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12030 	ipsec_stack_t	*ipss;
12031 	ip_stack_t	*ipst;
12032 
12033 	ASSERT(mctl_present || !secure);
12034 
12035 	ASSERT((ipha == NULL && ip6h != NULL) ||
12036 	    (ip6h == NULL && ipha != NULL));
12037 
12038 	/*
12039 	 * We don't necessarily have an ipsec_in_act action to verify
12040 	 * policy because of assymetrical policy where we have only
12041 	 * outbound policy and no inbound policy (possible with global
12042 	 * policy).
12043 	 */
12044 	if (!secure) {
12045 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12046 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12047 			return (B_TRUE);
12048 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12049 		    "tcp_check_policy", ipha, ip6h, secure,
12050 		    tcps->tcps_netstack);
12051 		ipss = tcps->tcps_netstack->netstack_ipsec;
12052 
12053 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12054 		    DROPPER(ipss, ipds_tcp_clear),
12055 		    &tcps->tcps_dropper);
12056 		return (B_FALSE);
12057 	}
12058 
12059 	/*
12060 	 * We have a secure packet.
12061 	 */
12062 	if (act == NULL) {
12063 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12064 		    "tcp_check_policy", ipha, ip6h, secure,
12065 		    tcps->tcps_netstack);
12066 		ipss = tcps->tcps_netstack->netstack_ipsec;
12067 
12068 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12069 		    DROPPER(ipss, ipds_tcp_secure),
12070 		    &tcps->tcps_dropper);
12071 		return (B_FALSE);
12072 	}
12073 
12074 	/*
12075 	 * XXX This whole routine is currently incorrect.  ipl should
12076 	 * be set to the latch pointer, but is currently not set, so
12077 	 * we initialize it to NULL to avoid picking up random garbage.
12078 	 */
12079 	if (ipl == NULL)
12080 		return (B_TRUE);
12081 
12082 	data_mp = first_mp->b_cont;
12083 
12084 	ii = (ipsec_in_t *)first_mp->b_rptr;
12085 
12086 	ipst = tcps->tcps_netstack->netstack_ip;
12087 
12088 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12089 	    &counter, tcp->tcp_connp)) {
12090 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12091 		return (B_TRUE);
12092 	}
12093 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12094 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12095 	    reason);
12096 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12097 
12098 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12099 	    &tcps->tcps_dropper);
12100 	return (B_FALSE);
12101 }
12102 
12103 /*
12104  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12105  * retransmission after a timeout.
12106  *
12107  * To limit the number of duplicate segments, we limit the number of segment
12108  * to be sent in one time to tcp_snd_burst, the burst variable.
12109  */
12110 static void
12111 tcp_ss_rexmit(tcp_t *tcp)
12112 {
12113 	uint32_t	snxt;
12114 	uint32_t	smax;
12115 	int32_t		win;
12116 	int32_t		mss;
12117 	int32_t		off;
12118 	int32_t		burst = tcp->tcp_snd_burst;
12119 	mblk_t		*snxt_mp;
12120 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12121 
12122 	/*
12123 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12124 	 * all unack'ed segments.
12125 	 */
12126 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12127 		smax = tcp->tcp_rexmit_max;
12128 		snxt = tcp->tcp_rexmit_nxt;
12129 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12130 			snxt = tcp->tcp_suna;
12131 		}
12132 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12133 		win -= snxt - tcp->tcp_suna;
12134 		mss = tcp->tcp_mss;
12135 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12136 
12137 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12138 		    (burst > 0) && (snxt_mp != NULL)) {
12139 			mblk_t	*xmit_mp;
12140 			mblk_t	*old_snxt_mp = snxt_mp;
12141 			uint32_t cnt = mss;
12142 
12143 			if (win < cnt) {
12144 				cnt = win;
12145 			}
12146 			if (SEQ_GT(snxt + cnt, smax)) {
12147 				cnt = smax - snxt;
12148 			}
12149 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12150 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12151 			if (xmit_mp == NULL)
12152 				return;
12153 
12154 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12155 
12156 			snxt += cnt;
12157 			win -= cnt;
12158 			/*
12159 			 * Update the send timestamp to avoid false
12160 			 * retransmission.
12161 			 */
12162 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12163 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12164 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12165 
12166 			tcp->tcp_rexmit_nxt = snxt;
12167 			burst--;
12168 		}
12169 		/*
12170 		 * If we have transmitted all we have at the time
12171 		 * we started the retranmission, we can leave
12172 		 * the rest of the job to tcp_wput_data().  But we
12173 		 * need to check the send window first.  If the
12174 		 * win is not 0, go on with tcp_wput_data().
12175 		 */
12176 		if (SEQ_LT(snxt, smax) || win == 0) {
12177 			return;
12178 		}
12179 	}
12180 	/* Only call tcp_wput_data() if there is data to be sent. */
12181 	if (tcp->tcp_unsent) {
12182 		tcp_wput_data(tcp, NULL, B_FALSE);
12183 	}
12184 }
12185 
12186 /*
12187  * Process all TCP option in SYN segment.  Note that this function should
12188  * be called after tcp_adapt_ire() is called so that the necessary info
12189  * from IRE is already set in the tcp structure.
12190  *
12191  * This function sets up the correct tcp_mss value according to the
12192  * MSS option value and our header size.  It also sets up the window scale
12193  * and timestamp values, and initialize SACK info blocks.  But it does not
12194  * change receive window size after setting the tcp_mss value.  The caller
12195  * should do the appropriate change.
12196  */
12197 void
12198 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12199 {
12200 	int options;
12201 	tcp_opt_t tcpopt;
12202 	uint32_t mss_max;
12203 	char *tmp_tcph;
12204 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12205 
12206 	tcpopt.tcp = NULL;
12207 	options = tcp_parse_options(tcph, &tcpopt);
12208 
12209 	/*
12210 	 * Process MSS option.  Note that MSS option value does not account
12211 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12212 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12213 	 * IPv6.
12214 	 */
12215 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12216 		if (tcp->tcp_ipversion == IPV4_VERSION)
12217 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12218 		else
12219 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12220 	} else {
12221 		if (tcp->tcp_ipversion == IPV4_VERSION)
12222 			mss_max = tcps->tcps_mss_max_ipv4;
12223 		else
12224 			mss_max = tcps->tcps_mss_max_ipv6;
12225 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12226 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12227 		else if (tcpopt.tcp_opt_mss > mss_max)
12228 			tcpopt.tcp_opt_mss = mss_max;
12229 	}
12230 
12231 	/* Process Window Scale option. */
12232 	if (options & TCP_OPT_WSCALE_PRESENT) {
12233 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12234 		tcp->tcp_snd_ws_ok = B_TRUE;
12235 	} else {
12236 		tcp->tcp_snd_ws = B_FALSE;
12237 		tcp->tcp_snd_ws_ok = B_FALSE;
12238 		tcp->tcp_rcv_ws = B_FALSE;
12239 	}
12240 
12241 	/* Process Timestamp option. */
12242 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12243 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12244 		tmp_tcph = (char *)tcp->tcp_tcph;
12245 
12246 		tcp->tcp_snd_ts_ok = B_TRUE;
12247 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12248 		tcp->tcp_last_rcv_lbolt = lbolt64;
12249 		ASSERT(OK_32PTR(tmp_tcph));
12250 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12251 
12252 		/* Fill in our template header with basic timestamp option. */
12253 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12254 		tmp_tcph[0] = TCPOPT_NOP;
12255 		tmp_tcph[1] = TCPOPT_NOP;
12256 		tmp_tcph[2] = TCPOPT_TSTAMP;
12257 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12258 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12259 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12260 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12261 	} else {
12262 		tcp->tcp_snd_ts_ok = B_FALSE;
12263 	}
12264 
12265 	/*
12266 	 * Process SACK options.  If SACK is enabled for this connection,
12267 	 * then allocate the SACK info structure.  Note the following ways
12268 	 * when tcp_snd_sack_ok is set to true.
12269 	 *
12270 	 * For active connection: in tcp_adapt_ire() called in
12271 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12272 	 * is checked.
12273 	 *
12274 	 * For passive connection: in tcp_adapt_ire() called in
12275 	 * tcp_accept_comm().
12276 	 *
12277 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12278 	 * That check makes sure that if we did not send a SACK OK option,
12279 	 * we will not enable SACK for this connection even though the other
12280 	 * side sends us SACK OK option.  For active connection, the SACK
12281 	 * info structure has already been allocated.  So we need to free
12282 	 * it if SACK is disabled.
12283 	 */
12284 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12285 	    (tcp->tcp_snd_sack_ok ||
12286 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12287 		/* This should be true only in the passive case. */
12288 		if (tcp->tcp_sack_info == NULL) {
12289 			ASSERT(TCP_IS_DETACHED(tcp));
12290 			tcp->tcp_sack_info =
12291 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12292 		}
12293 		if (tcp->tcp_sack_info == NULL) {
12294 			tcp->tcp_snd_sack_ok = B_FALSE;
12295 		} else {
12296 			tcp->tcp_snd_sack_ok = B_TRUE;
12297 			if (tcp->tcp_snd_ts_ok) {
12298 				tcp->tcp_max_sack_blk = 3;
12299 			} else {
12300 				tcp->tcp_max_sack_blk = 4;
12301 			}
12302 		}
12303 	} else {
12304 		/*
12305 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12306 		 * no SACK info will be used for this
12307 		 * connection.  This assumes that SACK usage
12308 		 * permission is negotiated.  This may need
12309 		 * to be changed once this is clarified.
12310 		 */
12311 		if (tcp->tcp_sack_info != NULL) {
12312 			ASSERT(tcp->tcp_notsack_list == NULL);
12313 			kmem_cache_free(tcp_sack_info_cache,
12314 			    tcp->tcp_sack_info);
12315 			tcp->tcp_sack_info = NULL;
12316 		}
12317 		tcp->tcp_snd_sack_ok = B_FALSE;
12318 	}
12319 
12320 	/*
12321 	 * Now we know the exact TCP/IP header length, subtract
12322 	 * that from tcp_mss to get our side's MSS.
12323 	 */
12324 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12325 	/*
12326 	 * Here we assume that the other side's header size will be equal to
12327 	 * our header size.  We calculate the real MSS accordingly.  Need to
12328 	 * take into additional stuffs IPsec puts in.
12329 	 *
12330 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12331 	 */
12332 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12333 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12334 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12335 
12336 	/*
12337 	 * Set MSS to the smaller one of both ends of the connection.
12338 	 * We should not have called tcp_mss_set() before, but our
12339 	 * side of the MSS should have been set to a proper value
12340 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12341 	 * STREAM head parameters properly.
12342 	 *
12343 	 * If we have a larger-than-16-bit window but the other side
12344 	 * didn't want to do window scale, tcp_rwnd_set() will take
12345 	 * care of that.
12346 	 */
12347 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12348 }
12349 
12350 /*
12351  * Sends the T_CONN_IND to the listener. The caller calls this
12352  * functions via squeue to get inside the listener's perimeter
12353  * once the 3 way hand shake is done a T_CONN_IND needs to be
12354  * sent. As an optimization, the caller can call this directly
12355  * if listener's perimeter is same as eager's.
12356  */
12357 /* ARGSUSED */
12358 void
12359 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12360 {
12361 	conn_t			*lconnp = (conn_t *)arg;
12362 	tcp_t			*listener = lconnp->conn_tcp;
12363 	tcp_t			*tcp;
12364 	struct T_conn_ind	*conn_ind;
12365 	ipaddr_t 		*addr_cache;
12366 	boolean_t		need_send_conn_ind = B_FALSE;
12367 	tcp_stack_t		*tcps = listener->tcp_tcps;
12368 
12369 	/* retrieve the eager */
12370 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12371 	ASSERT(conn_ind->OPT_offset != 0 &&
12372 	    conn_ind->OPT_length == sizeof (intptr_t));
12373 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12374 	    conn_ind->OPT_length);
12375 
12376 	/*
12377 	 * TLI/XTI applications will get confused by
12378 	 * sending eager as an option since it violates
12379 	 * the option semantics. So remove the eager as
12380 	 * option since TLI/XTI app doesn't need it anyway.
12381 	 */
12382 	if (!TCP_IS_SOCKET(listener)) {
12383 		conn_ind->OPT_length = 0;
12384 		conn_ind->OPT_offset = 0;
12385 	}
12386 	if (listener->tcp_state != TCPS_LISTEN) {
12387 		/*
12388 		 * If listener has closed, it would have caused a
12389 		 * a cleanup/blowoff to happen for the eager. We
12390 		 * just need to return.
12391 		 */
12392 		freemsg(mp);
12393 		return;
12394 	}
12395 
12396 
12397 	/*
12398 	 * if the conn_req_q is full defer passing up the
12399 	 * T_CONN_IND until space is availabe after t_accept()
12400 	 * processing
12401 	 */
12402 	mutex_enter(&listener->tcp_eager_lock);
12403 
12404 	/*
12405 	 * Take the eager out, if it is in the list of droppable eagers
12406 	 * as we are here because the 3W handshake is over.
12407 	 */
12408 	MAKE_UNDROPPABLE(tcp);
12409 
12410 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12411 		tcp_t *tail;
12412 
12413 		/*
12414 		 * The eager already has an extra ref put in tcp_rput_data
12415 		 * so that it stays till accept comes back even though it
12416 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12417 		 */
12418 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12419 		listener->tcp_conn_req_cnt_q0--;
12420 		listener->tcp_conn_req_cnt_q++;
12421 
12422 		/* Move from SYN_RCVD to ESTABLISHED list  */
12423 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12424 		    tcp->tcp_eager_prev_q0;
12425 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12426 		    tcp->tcp_eager_next_q0;
12427 		tcp->tcp_eager_prev_q0 = NULL;
12428 		tcp->tcp_eager_next_q0 = NULL;
12429 
12430 		/*
12431 		 * Insert at end of the queue because sockfs
12432 		 * sends down T_CONN_RES in chronological
12433 		 * order. Leaving the older conn indications
12434 		 * at front of the queue helps reducing search
12435 		 * time.
12436 		 */
12437 		tail = listener->tcp_eager_last_q;
12438 		if (tail != NULL)
12439 			tail->tcp_eager_next_q = tcp;
12440 		else
12441 			listener->tcp_eager_next_q = tcp;
12442 		listener->tcp_eager_last_q = tcp;
12443 		tcp->tcp_eager_next_q = NULL;
12444 		/*
12445 		 * Delay sending up the T_conn_ind until we are
12446 		 * done with the eager. Once we have have sent up
12447 		 * the T_conn_ind, the accept can potentially complete
12448 		 * any time and release the refhold we have on the eager.
12449 		 */
12450 		need_send_conn_ind = B_TRUE;
12451 	} else {
12452 		/*
12453 		 * Defer connection on q0 and set deferred
12454 		 * connection bit true
12455 		 */
12456 		tcp->tcp_conn_def_q0 = B_TRUE;
12457 
12458 		/* take tcp out of q0 ... */
12459 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12460 		    tcp->tcp_eager_next_q0;
12461 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12462 		    tcp->tcp_eager_prev_q0;
12463 
12464 		/* ... and place it at the end of q0 */
12465 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12466 		tcp->tcp_eager_next_q0 = listener;
12467 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12468 		listener->tcp_eager_prev_q0 = tcp;
12469 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12470 	}
12471 
12472 	/* we have timed out before */
12473 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12474 		tcp->tcp_syn_rcvd_timeout = 0;
12475 		listener->tcp_syn_rcvd_timeout--;
12476 		if (listener->tcp_syn_defense &&
12477 		    listener->tcp_syn_rcvd_timeout <=
12478 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12479 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12480 		    listener->tcp_last_rcv_lbolt)) {
12481 			/*
12482 			 * Turn off the defense mode if we
12483 			 * believe the SYN attack is over.
12484 			 */
12485 			listener->tcp_syn_defense = B_FALSE;
12486 			if (listener->tcp_ip_addr_cache) {
12487 				kmem_free((void *)listener->tcp_ip_addr_cache,
12488 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12489 				listener->tcp_ip_addr_cache = NULL;
12490 			}
12491 		}
12492 	}
12493 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12494 	if (addr_cache != NULL) {
12495 		/*
12496 		 * We have finished a 3-way handshake with this
12497 		 * remote host. This proves the IP addr is good.
12498 		 * Cache it!
12499 		 */
12500 		addr_cache[IP_ADDR_CACHE_HASH(
12501 		    tcp->tcp_remote)] = tcp->tcp_remote;
12502 	}
12503 	mutex_exit(&listener->tcp_eager_lock);
12504 	if (need_send_conn_ind)
12505 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12506 }
12507 
12508 /*
12509  * Send the newconn notification to ulp. The eager is blown off if the
12510  * notification fails.
12511  */
12512 static void
12513 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12514 {
12515 	if (IPCL_IS_NONSTR(lconnp)) {
12516 		cred_t	*cr;
12517 		pid_t	cpid;
12518 
12519 		cr = msg_getcred(mp, &cpid);
12520 
12521 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12522 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12523 		    lconnp->conn_tcp);
12524 
12525 		/* Keep the message around in case of a fallback to TPI */
12526 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12527 
12528 		/*
12529 		 * Notify the ULP about the newconn. It is guaranteed that no
12530 		 * tcp_accept() call will be made for the eager if the
12531 		 * notification fails, so it's safe to blow it off in that
12532 		 * case.
12533 		 *
12534 		 * The upper handle will be assigned when tcp_accept() is
12535 		 * called.
12536 		 */
12537 		if ((*lconnp->conn_upcalls->su_newconn)
12538 		    (lconnp->conn_upper_handle,
12539 		    (sock_lower_handle_t)econnp,
12540 		    &sock_tcp_downcalls, cr, cpid,
12541 		    &econnp->conn_upcalls) == NULL) {
12542 			/* Failed to allocate a socket */
12543 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12544 			    tcpEstabResets);
12545 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12546 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12547 		}
12548 	} else {
12549 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12550 	}
12551 }
12552 
12553 mblk_t *
12554 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12555     uint_t *ifindexp, ip6_pkt_t *ippp)
12556 {
12557 	ip_pktinfo_t	*pinfo;
12558 	ip6_t		*ip6h;
12559 	uchar_t		*rptr;
12560 	mblk_t		*first_mp = mp;
12561 	boolean_t	mctl_present = B_FALSE;
12562 	uint_t 		ifindex = 0;
12563 	ip6_pkt_t	ipp;
12564 	uint_t		ipvers;
12565 	uint_t		ip_hdr_len;
12566 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12567 
12568 	rptr = mp->b_rptr;
12569 	ASSERT(OK_32PTR(rptr));
12570 	ASSERT(tcp != NULL);
12571 	ipp.ipp_fields = 0;
12572 
12573 	switch DB_TYPE(mp) {
12574 	case M_CTL:
12575 		mp = mp->b_cont;
12576 		if (mp == NULL) {
12577 			freemsg(first_mp);
12578 			return (NULL);
12579 		}
12580 		if (DB_TYPE(mp) != M_DATA) {
12581 			freemsg(first_mp);
12582 			return (NULL);
12583 		}
12584 		mctl_present = B_TRUE;
12585 		break;
12586 	case M_DATA:
12587 		break;
12588 	default:
12589 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12590 		freemsg(mp);
12591 		return (NULL);
12592 	}
12593 	ipvers = IPH_HDR_VERSION(rptr);
12594 	if (ipvers == IPV4_VERSION) {
12595 		if (tcp == NULL) {
12596 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12597 			goto done;
12598 		}
12599 
12600 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12601 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12602 
12603 		/*
12604 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12605 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12606 		 */
12607 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12608 		    mctl_present) {
12609 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12610 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12611 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12612 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12613 				ipp.ipp_fields |= IPPF_IFINDEX;
12614 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12615 				ifindex = pinfo->ip_pkt_ifindex;
12616 			}
12617 			freeb(first_mp);
12618 			mctl_present = B_FALSE;
12619 		}
12620 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12621 	} else {
12622 		ip6h = (ip6_t *)rptr;
12623 
12624 		ASSERT(ipvers == IPV6_VERSION);
12625 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12626 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12627 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12628 
12629 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12630 			uint8_t	nexthdrp;
12631 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12632 
12633 			/* Look for ifindex information */
12634 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12635 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12636 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12637 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12638 					freemsg(first_mp);
12639 					return (NULL);
12640 				}
12641 
12642 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12643 					ASSERT(ip6i->ip6i_ifindex != 0);
12644 					ipp.ipp_fields |= IPPF_IFINDEX;
12645 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12646 					ifindex = ip6i->ip6i_ifindex;
12647 				}
12648 				rptr = (uchar_t *)&ip6i[1];
12649 				mp->b_rptr = rptr;
12650 				if (rptr == mp->b_wptr) {
12651 					mblk_t *mp1;
12652 					mp1 = mp->b_cont;
12653 					freeb(mp);
12654 					mp = mp1;
12655 					rptr = mp->b_rptr;
12656 				}
12657 				if (MBLKL(mp) < IPV6_HDR_LEN +
12658 				    sizeof (tcph_t)) {
12659 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12660 					freemsg(first_mp);
12661 					return (NULL);
12662 				}
12663 				ip6h = (ip6_t *)rptr;
12664 			}
12665 
12666 			/*
12667 			 * Find any potentially interesting extension headers
12668 			 * as well as the length of the IPv6 + extension
12669 			 * headers.
12670 			 */
12671 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12672 			/* Verify if this is a TCP packet */
12673 			if (nexthdrp != IPPROTO_TCP) {
12674 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12675 				freemsg(first_mp);
12676 				return (NULL);
12677 			}
12678 		} else {
12679 			ip_hdr_len = IPV6_HDR_LEN;
12680 		}
12681 	}
12682 
12683 done:
12684 	if (ipversp != NULL)
12685 		*ipversp = ipvers;
12686 	if (ip_hdr_lenp != NULL)
12687 		*ip_hdr_lenp = ip_hdr_len;
12688 	if (ippp != NULL)
12689 		*ippp = ipp;
12690 	if (ifindexp != NULL)
12691 		*ifindexp = ifindex;
12692 	if (mctl_present) {
12693 		freeb(first_mp);
12694 	}
12695 	return (mp);
12696 }
12697 
12698 /*
12699  * Handle M_DATA messages from IP. Its called directly from IP via
12700  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12701  * in this path.
12702  *
12703  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12704  * v4 and v6), we are called through tcp_input() and a M_CTL can
12705  * be present for options but tcp_find_pktinfo() deals with it. We
12706  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12707  *
12708  * The first argument is always the connp/tcp to which the mp belongs.
12709  * There are no exceptions to this rule. The caller has already put
12710  * a reference on this connp/tcp and once tcp_rput_data() returns,
12711  * the squeue will do the refrele.
12712  *
12713  * The TH_SYN for the listener directly go to tcp_conn_request via
12714  * squeue.
12715  *
12716  * sqp: NULL = recursive, sqp != NULL means called from squeue
12717  */
12718 void
12719 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12720 {
12721 	int32_t		bytes_acked;
12722 	int32_t		gap;
12723 	mblk_t		*mp1;
12724 	uint_t		flags;
12725 	uint32_t	new_swnd = 0;
12726 	uchar_t		*iphdr;
12727 	uchar_t		*rptr;
12728 	int32_t		rgap;
12729 	uint32_t	seg_ack;
12730 	int		seg_len;
12731 	uint_t		ip_hdr_len;
12732 	uint32_t	seg_seq;
12733 	tcph_t		*tcph;
12734 	int		urp;
12735 	tcp_opt_t	tcpopt;
12736 	uint_t		ipvers;
12737 	ip6_pkt_t	ipp;
12738 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12739 	uint32_t	cwnd;
12740 	uint32_t	add;
12741 	int		npkt;
12742 	int		mss;
12743 	conn_t		*connp = (conn_t *)arg;
12744 	squeue_t	*sqp = (squeue_t *)arg2;
12745 	tcp_t		*tcp = connp->conn_tcp;
12746 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12747 
12748 	/*
12749 	 * RST from fused tcp loopback peer should trigger an unfuse.
12750 	 */
12751 	if (tcp->tcp_fused) {
12752 		TCP_STAT(tcps, tcp_fusion_aborted);
12753 		tcp_unfuse(tcp);
12754 	}
12755 
12756 	iphdr = mp->b_rptr;
12757 	rptr = mp->b_rptr;
12758 	ASSERT(OK_32PTR(rptr));
12759 
12760 	/*
12761 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12762 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12763 	 * necessary information.
12764 	 */
12765 	if (IPCL_IS_TCP4(connp)) {
12766 		ipvers = IPV4_VERSION;
12767 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12768 	} else {
12769 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12770 		    NULL, &ipp);
12771 		if (mp == NULL) {
12772 			TCP_STAT(tcps, tcp_rput_v6_error);
12773 			return;
12774 		}
12775 		iphdr = mp->b_rptr;
12776 		rptr = mp->b_rptr;
12777 	}
12778 	ASSERT(DB_TYPE(mp) == M_DATA);
12779 	ASSERT(mp->b_next == NULL);
12780 
12781 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12782 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12783 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12784 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12785 	seg_len = (int)(mp->b_wptr - rptr) -
12786 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12787 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12788 		do {
12789 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12790 			    (uintptr_t)INT_MAX);
12791 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12792 		} while ((mp1 = mp1->b_cont) != NULL &&
12793 		    mp1->b_datap->db_type == M_DATA);
12794 	}
12795 
12796 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12797 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12798 		    seg_len, tcph);
12799 		return;
12800 	}
12801 
12802 	if (sqp != NULL) {
12803 		/*
12804 		 * This is the correct place to update tcp_last_recv_time. Note
12805 		 * that it is also updated for tcp structure that belongs to
12806 		 * global and listener queues which do not really need updating.
12807 		 * But that should not cause any harm.  And it is updated for
12808 		 * all kinds of incoming segments, not only for data segments.
12809 		 */
12810 		tcp->tcp_last_recv_time = lbolt;
12811 	}
12812 
12813 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12814 
12815 	BUMP_LOCAL(tcp->tcp_ibsegs);
12816 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12817 
12818 	if ((flags & TH_URG) && sqp != NULL) {
12819 		/*
12820 		 * TCP can't handle urgent pointers that arrive before
12821 		 * the connection has been accept()ed since it can't
12822 		 * buffer OOB data.  Discard segment if this happens.
12823 		 *
12824 		 * We can't just rely on a non-null tcp_listener to indicate
12825 		 * that the accept() has completed since unlinking of the
12826 		 * eager and completion of the accept are not atomic.
12827 		 * tcp_detached, when it is not set (B_FALSE) indicates
12828 		 * that the accept() has completed.
12829 		 *
12830 		 * Nor can it reassemble urgent pointers, so discard
12831 		 * if it's not the next segment expected.
12832 		 *
12833 		 * Otherwise, collapse chain into one mblk (discard if
12834 		 * that fails).  This makes sure the headers, retransmitted
12835 		 * data, and new data all are in the same mblk.
12836 		 */
12837 		ASSERT(mp != NULL);
12838 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12839 			freemsg(mp);
12840 			return;
12841 		}
12842 		/* Update pointers into message */
12843 		iphdr = rptr = mp->b_rptr;
12844 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12845 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12846 			/*
12847 			 * Since we can't handle any data with this urgent
12848 			 * pointer that is out of sequence, we expunge
12849 			 * the data.  This allows us to still register
12850 			 * the urgent mark and generate the M_PCSIG,
12851 			 * which we can do.
12852 			 */
12853 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12854 			seg_len = 0;
12855 		}
12856 	}
12857 
12858 	switch (tcp->tcp_state) {
12859 	case TCPS_SYN_SENT:
12860 		if (flags & TH_ACK) {
12861 			/*
12862 			 * Note that our stack cannot send data before a
12863 			 * connection is established, therefore the
12864 			 * following check is valid.  Otherwise, it has
12865 			 * to be changed.
12866 			 */
12867 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12868 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12869 				freemsg(mp);
12870 				if (flags & TH_RST)
12871 					return;
12872 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12873 				    tcp, seg_ack, 0, TH_RST);
12874 				return;
12875 			}
12876 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12877 		}
12878 		if (flags & TH_RST) {
12879 			freemsg(mp);
12880 			if (flags & TH_ACK)
12881 				(void) tcp_clean_death(tcp,
12882 				    ECONNREFUSED, 13);
12883 			return;
12884 		}
12885 		if (!(flags & TH_SYN)) {
12886 			freemsg(mp);
12887 			return;
12888 		}
12889 
12890 		/* Process all TCP options. */
12891 		tcp_process_options(tcp, tcph);
12892 		/*
12893 		 * The following changes our rwnd to be a multiple of the
12894 		 * MIN(peer MSS, our MSS) for performance reason.
12895 		 */
12896 		(void) tcp_rwnd_set(tcp,
12897 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
12898 
12899 		/* Is the other end ECN capable? */
12900 		if (tcp->tcp_ecn_ok) {
12901 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12902 				tcp->tcp_ecn_ok = B_FALSE;
12903 			}
12904 		}
12905 		/*
12906 		 * Clear ECN flags because it may interfere with later
12907 		 * processing.
12908 		 */
12909 		flags &= ~(TH_ECE|TH_CWR);
12910 
12911 		tcp->tcp_irs = seg_seq;
12912 		tcp->tcp_rack = seg_seq;
12913 		tcp->tcp_rnxt = seg_seq + 1;
12914 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12915 		if (!TCP_IS_DETACHED(tcp)) {
12916 			/* Allocate room for SACK options if needed. */
12917 			if (tcp->tcp_snd_sack_ok) {
12918 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12919 				    tcp->tcp_hdr_len +
12920 				    TCPOPT_MAX_SACK_LEN +
12921 				    (tcp->tcp_loopback ? 0 :
12922 				    tcps->tcps_wroff_xtra));
12923 			} else {
12924 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
12925 				    tcp->tcp_hdr_len +
12926 				    (tcp->tcp_loopback ? 0 :
12927 				    tcps->tcps_wroff_xtra));
12928 			}
12929 		}
12930 		if (flags & TH_ACK) {
12931 			/*
12932 			 * If we can't get the confirmation upstream, pretend
12933 			 * we didn't even see this one.
12934 			 *
12935 			 * XXX: how can we pretend we didn't see it if we
12936 			 * have updated rnxt et. al.
12937 			 *
12938 			 * For loopback we defer sending up the T_CONN_CON
12939 			 * until after some checks below.
12940 			 */
12941 			mp1 = NULL;
12942 			/*
12943 			 * tcp_sendmsg() checks tcp_state without entering
12944 			 * the squeue so tcp_state should be updated before
12945 			 * sending up connection confirmation
12946 			 */
12947 			tcp->tcp_state = TCPS_ESTABLISHED;
12948 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12949 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12950 				tcp->tcp_state = TCPS_SYN_SENT;
12951 				freemsg(mp);
12952 				return;
12953 			}
12954 			/* SYN was acked - making progress */
12955 			if (tcp->tcp_ipversion == IPV6_VERSION)
12956 				tcp->tcp_ip_forward_progress = B_TRUE;
12957 
12958 			/* One for the SYN */
12959 			tcp->tcp_suna = tcp->tcp_iss + 1;
12960 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12961 
12962 			/*
12963 			 * If SYN was retransmitted, need to reset all
12964 			 * retransmission info.  This is because this
12965 			 * segment will be treated as a dup ACK.
12966 			 */
12967 			if (tcp->tcp_rexmit) {
12968 				tcp->tcp_rexmit = B_FALSE;
12969 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12970 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12971 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12972 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12973 				tcp->tcp_ms_we_have_waited = 0;
12974 
12975 				/*
12976 				 * Set tcp_cwnd back to 1 MSS, per
12977 				 * recommendation from
12978 				 * draft-floyd-incr-init-win-01.txt,
12979 				 * Increasing TCP's Initial Window.
12980 				 */
12981 				tcp->tcp_cwnd = tcp->tcp_mss;
12982 			}
12983 
12984 			tcp->tcp_swl1 = seg_seq;
12985 			tcp->tcp_swl2 = seg_ack;
12986 
12987 			new_swnd = BE16_TO_U16(tcph->th_win);
12988 			tcp->tcp_swnd = new_swnd;
12989 			if (new_swnd > tcp->tcp_max_swnd)
12990 				tcp->tcp_max_swnd = new_swnd;
12991 
12992 			/*
12993 			 * Always send the three-way handshake ack immediately
12994 			 * in order to make the connection complete as soon as
12995 			 * possible on the accepting host.
12996 			 */
12997 			flags |= TH_ACK_NEEDED;
12998 
12999 			/*
13000 			 * Special case for loopback.  At this point we have
13001 			 * received SYN-ACK from the remote endpoint.  In
13002 			 * order to ensure that both endpoints reach the
13003 			 * fused state prior to any data exchange, the final
13004 			 * ACK needs to be sent before we indicate T_CONN_CON
13005 			 * to the module upstream.
13006 			 */
13007 			if (tcp->tcp_loopback) {
13008 				mblk_t *ack_mp;
13009 
13010 				ASSERT(!tcp->tcp_unfusable);
13011 				ASSERT(mp1 != NULL);
13012 				/*
13013 				 * For loopback, we always get a pure SYN-ACK
13014 				 * and only need to send back the final ACK
13015 				 * with no data (this is because the other
13016 				 * tcp is ours and we don't do T/TCP).  This
13017 				 * final ACK triggers the passive side to
13018 				 * perform fusion in ESTABLISHED state.
13019 				 */
13020 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13021 					if (tcp->tcp_ack_tid != 0) {
13022 						(void) TCP_TIMER_CANCEL(tcp,
13023 						    tcp->tcp_ack_tid);
13024 						tcp->tcp_ack_tid = 0;
13025 					}
13026 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13027 					BUMP_LOCAL(tcp->tcp_obsegs);
13028 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13029 
13030 					if (!IPCL_IS_NONSTR(connp)) {
13031 						/* Send up T_CONN_CON */
13032 						putnext(tcp->tcp_rq, mp1);
13033 					} else {
13034 						cred_t	*cr;
13035 						pid_t	cpid;
13036 
13037 						cr = msg_getcred(mp1, &cpid);
13038 						(*connp->conn_upcalls->
13039 						    su_connected)
13040 						    (connp->conn_upper_handle,
13041 						    tcp->tcp_connid, cr, cpid);
13042 						freemsg(mp1);
13043 					}
13044 
13045 					freemsg(mp);
13046 					return;
13047 				}
13048 				/*
13049 				 * Forget fusion; we need to handle more
13050 				 * complex cases below.  Send the deferred
13051 				 * T_CONN_CON message upstream and proceed
13052 				 * as usual.  Mark this tcp as not capable
13053 				 * of fusion.
13054 				 */
13055 				TCP_STAT(tcps, tcp_fusion_unfusable);
13056 				tcp->tcp_unfusable = B_TRUE;
13057 				if (!IPCL_IS_NONSTR(connp)) {
13058 					putnext(tcp->tcp_rq, mp1);
13059 				} else {
13060 					cred_t	*cr;
13061 					pid_t	cpid;
13062 
13063 					cr = msg_getcred(mp1, &cpid);
13064 					(*connp->conn_upcalls->su_connected)
13065 					    (connp->conn_upper_handle,
13066 					    tcp->tcp_connid, cr, cpid);
13067 					freemsg(mp1);
13068 				}
13069 			}
13070 
13071 			/*
13072 			 * Check to see if there is data to be sent.  If
13073 			 * yes, set the transmit flag.  Then check to see
13074 			 * if received data processing needs to be done.
13075 			 * If not, go straight to xmit_check.  This short
13076 			 * cut is OK as we don't support T/TCP.
13077 			 */
13078 			if (tcp->tcp_unsent)
13079 				flags |= TH_XMIT_NEEDED;
13080 
13081 			if (seg_len == 0 && !(flags & TH_URG)) {
13082 				freemsg(mp);
13083 				goto xmit_check;
13084 			}
13085 
13086 			flags &= ~TH_SYN;
13087 			seg_seq++;
13088 			break;
13089 		}
13090 		tcp->tcp_state = TCPS_SYN_RCVD;
13091 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13092 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13093 		if (mp1) {
13094 			/*
13095 			 * See comment in tcp_conn_request() for why we use
13096 			 * the open() time pid here.
13097 			 */
13098 			DB_CPID(mp1) = tcp->tcp_cpid;
13099 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13100 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13101 		}
13102 		freemsg(mp);
13103 		return;
13104 	case TCPS_SYN_RCVD:
13105 		if (flags & TH_ACK) {
13106 			/*
13107 			 * In this state, a SYN|ACK packet is either bogus
13108 			 * because the other side must be ACKing our SYN which
13109 			 * indicates it has seen the ACK for their SYN and
13110 			 * shouldn't retransmit it or we're crossing SYNs
13111 			 * on active open.
13112 			 */
13113 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13114 				freemsg(mp);
13115 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13116 				    tcp, seg_ack, 0, TH_RST);
13117 				return;
13118 			}
13119 			/*
13120 			 * NOTE: RFC 793 pg. 72 says this should be
13121 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13122 			 * but that would mean we have an ack that ignored
13123 			 * our SYN.
13124 			 */
13125 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13126 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13127 				freemsg(mp);
13128 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13129 				    tcp, seg_ack, 0, TH_RST);
13130 				return;
13131 			}
13132 		}
13133 		break;
13134 	case TCPS_LISTEN:
13135 		/*
13136 		 * Only a TLI listener can come through this path when a
13137 		 * acceptor is going back to be a listener and a packet
13138 		 * for the acceptor hits the classifier. For a socket
13139 		 * listener, this can never happen because a listener
13140 		 * can never accept connection on itself and hence a
13141 		 * socket acceptor can not go back to being a listener.
13142 		 */
13143 		ASSERT(!TCP_IS_SOCKET(tcp));
13144 		/*FALLTHRU*/
13145 	case TCPS_CLOSED:
13146 	case TCPS_BOUND: {
13147 		conn_t	*new_connp;
13148 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13149 
13150 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13151 		if (new_connp != NULL) {
13152 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13153 			return;
13154 		}
13155 		/* We failed to classify. For now just drop the packet */
13156 		freemsg(mp);
13157 		return;
13158 	}
13159 	case TCPS_IDLE:
13160 		/*
13161 		 * Handle the case where the tcp_clean_death() has happened
13162 		 * on a connection (application hasn't closed yet) but a packet
13163 		 * was already queued on squeue before tcp_clean_death()
13164 		 * was processed. Calling tcp_clean_death() twice on same
13165 		 * connection can result in weird behaviour.
13166 		 */
13167 		freemsg(mp);
13168 		return;
13169 	default:
13170 		break;
13171 	}
13172 
13173 	/*
13174 	 * Already on the correct queue/perimeter.
13175 	 * If this is a detached connection and not an eager
13176 	 * connection hanging off a listener then new data
13177 	 * (past the FIN) will cause a reset.
13178 	 * We do a special check here where it
13179 	 * is out of the main line, rather than check
13180 	 * if we are detached every time we see new
13181 	 * data down below.
13182 	 */
13183 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13184 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13185 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13186 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13187 
13188 		freemsg(mp);
13189 		/*
13190 		 * This could be an SSL closure alert. We're detached so just
13191 		 * acknowledge it this last time.
13192 		 */
13193 		if (tcp->tcp_kssl_ctx != NULL) {
13194 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13195 			tcp->tcp_kssl_ctx = NULL;
13196 
13197 			tcp->tcp_rnxt += seg_len;
13198 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13199 			flags |= TH_ACK_NEEDED;
13200 			goto ack_check;
13201 		}
13202 
13203 		tcp_xmit_ctl("new data when detached", tcp,
13204 		    tcp->tcp_snxt, 0, TH_RST);
13205 		(void) tcp_clean_death(tcp, EPROTO, 12);
13206 		return;
13207 	}
13208 
13209 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13210 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13211 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13212 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13213 
13214 	if (tcp->tcp_snd_ts_ok) {
13215 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13216 			/*
13217 			 * This segment is not acceptable.
13218 			 * Drop it and send back an ACK.
13219 			 */
13220 			freemsg(mp);
13221 			flags |= TH_ACK_NEEDED;
13222 			goto ack_check;
13223 		}
13224 	} else if (tcp->tcp_snd_sack_ok) {
13225 		ASSERT(tcp->tcp_sack_info != NULL);
13226 		tcpopt.tcp = tcp;
13227 		/*
13228 		 * SACK info in already updated in tcp_parse_options.  Ignore
13229 		 * all other TCP options...
13230 		 */
13231 		(void) tcp_parse_options(tcph, &tcpopt);
13232 	}
13233 try_again:;
13234 	mss = tcp->tcp_mss;
13235 	gap = seg_seq - tcp->tcp_rnxt;
13236 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13237 	/*
13238 	 * gap is the amount of sequence space between what we expect to see
13239 	 * and what we got for seg_seq.  A positive value for gap means
13240 	 * something got lost.  A negative value means we got some old stuff.
13241 	 */
13242 	if (gap < 0) {
13243 		/* Old stuff present.  Is the SYN in there? */
13244 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13245 		    (seg_len != 0)) {
13246 			flags &= ~TH_SYN;
13247 			seg_seq++;
13248 			urp--;
13249 			/* Recompute the gaps after noting the SYN. */
13250 			goto try_again;
13251 		}
13252 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13253 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13254 		    (seg_len > -gap ? -gap : seg_len));
13255 		/* Remove the old stuff from seg_len. */
13256 		seg_len += gap;
13257 		/*
13258 		 * Anything left?
13259 		 * Make sure to check for unack'd FIN when rest of data
13260 		 * has been previously ack'd.
13261 		 */
13262 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13263 			/*
13264 			 * Resets are only valid if they lie within our offered
13265 			 * window.  If the RST bit is set, we just ignore this
13266 			 * segment.
13267 			 */
13268 			if (flags & TH_RST) {
13269 				freemsg(mp);
13270 				return;
13271 			}
13272 
13273 			/*
13274 			 * The arriving of dup data packets indicate that we
13275 			 * may have postponed an ack for too long, or the other
13276 			 * side's RTT estimate is out of shape. Start acking
13277 			 * more often.
13278 			 */
13279 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13280 			    tcp->tcp_rack_cnt >= 1 &&
13281 			    tcp->tcp_rack_abs_max > 2) {
13282 				tcp->tcp_rack_abs_max--;
13283 			}
13284 			tcp->tcp_rack_cur_max = 1;
13285 
13286 			/*
13287 			 * This segment is "unacceptable".  None of its
13288 			 * sequence space lies within our advertized window.
13289 			 *
13290 			 * Adjust seg_len to the original value for tracing.
13291 			 */
13292 			seg_len -= gap;
13293 			if (tcp->tcp_debug) {
13294 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13295 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13296 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13297 				    "seg_len %d, rnxt %u, snxt %u, %s",
13298 				    gap, rgap, flags, seg_seq, seg_ack,
13299 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13300 				    tcp_display(tcp, NULL,
13301 				    DISP_ADDR_AND_PORT));
13302 			}
13303 
13304 			/*
13305 			 * Arrange to send an ACK in response to the
13306 			 * unacceptable segment per RFC 793 page 69. There
13307 			 * is only one small difference between ours and the
13308 			 * acceptability test in the RFC - we accept ACK-only
13309 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13310 			 * will be generated.
13311 			 *
13312 			 * Note that we have to ACK an ACK-only packet at least
13313 			 * for stacks that send 0-length keep-alives with
13314 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13315 			 * section 4.2.3.6. As long as we don't ever generate
13316 			 * an unacceptable packet in response to an incoming
13317 			 * packet that is unacceptable, it should not cause
13318 			 * "ACK wars".
13319 			 */
13320 			flags |=  TH_ACK_NEEDED;
13321 
13322 			/*
13323 			 * Continue processing this segment in order to use the
13324 			 * ACK information it contains, but skip all other
13325 			 * sequence-number processing.	Processing the ACK
13326 			 * information is necessary in order to
13327 			 * re-synchronize connections that may have lost
13328 			 * synchronization.
13329 			 *
13330 			 * We clear seg_len and flag fields related to
13331 			 * sequence number processing as they are not
13332 			 * to be trusted for an unacceptable segment.
13333 			 */
13334 			seg_len = 0;
13335 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13336 			goto process_ack;
13337 		}
13338 
13339 		/* Fix seg_seq, and chew the gap off the front. */
13340 		seg_seq = tcp->tcp_rnxt;
13341 		urp += gap;
13342 		do {
13343 			mblk_t	*mp2;
13344 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13345 			    (uintptr_t)UINT_MAX);
13346 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13347 			if (gap > 0) {
13348 				mp->b_rptr = mp->b_wptr - gap;
13349 				break;
13350 			}
13351 			mp2 = mp;
13352 			mp = mp->b_cont;
13353 			freeb(mp2);
13354 		} while (gap < 0);
13355 		/*
13356 		 * If the urgent data has already been acknowledged, we
13357 		 * should ignore TH_URG below
13358 		 */
13359 		if (urp < 0)
13360 			flags &= ~TH_URG;
13361 	}
13362 	/*
13363 	 * rgap is the amount of stuff received out of window.  A negative
13364 	 * value is the amount out of window.
13365 	 */
13366 	if (rgap < 0) {
13367 		mblk_t	*mp2;
13368 
13369 		if (tcp->tcp_rwnd == 0) {
13370 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13371 		} else {
13372 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13373 			UPDATE_MIB(&tcps->tcps_mib,
13374 			    tcpInDataPastWinBytes, -rgap);
13375 		}
13376 
13377 		/*
13378 		 * seg_len does not include the FIN, so if more than
13379 		 * just the FIN is out of window, we act like we don't
13380 		 * see it.  (If just the FIN is out of window, rgap
13381 		 * will be zero and we will go ahead and acknowledge
13382 		 * the FIN.)
13383 		 */
13384 		flags &= ~TH_FIN;
13385 
13386 		/* Fix seg_len and make sure there is something left. */
13387 		seg_len += rgap;
13388 		if (seg_len <= 0) {
13389 			/*
13390 			 * Resets are only valid if they lie within our offered
13391 			 * window.  If the RST bit is set, we just ignore this
13392 			 * segment.
13393 			 */
13394 			if (flags & TH_RST) {
13395 				freemsg(mp);
13396 				return;
13397 			}
13398 
13399 			/* Per RFC 793, we need to send back an ACK. */
13400 			flags |= TH_ACK_NEEDED;
13401 
13402 			/*
13403 			 * Send SIGURG as soon as possible i.e. even
13404 			 * if the TH_URG was delivered in a window probe
13405 			 * packet (which will be unacceptable).
13406 			 *
13407 			 * We generate a signal if none has been generated
13408 			 * for this connection or if this is a new urgent
13409 			 * byte. Also send a zero-length "unmarked" message
13410 			 * to inform SIOCATMARK that this is not the mark.
13411 			 *
13412 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13413 			 * is sent up. This plus the check for old data
13414 			 * (gap >= 0) handles the wraparound of the sequence
13415 			 * number space without having to always track the
13416 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13417 			 * this max in its rcv_up variable).
13418 			 *
13419 			 * This prevents duplicate SIGURGS due to a "late"
13420 			 * zero-window probe when the T_EXDATA_IND has already
13421 			 * been sent up.
13422 			 */
13423 			if ((flags & TH_URG) &&
13424 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13425 			    tcp->tcp_urp_last))) {
13426 				if (IPCL_IS_NONSTR(connp)) {
13427 					if (!TCP_IS_DETACHED(tcp)) {
13428 						(*connp->conn_upcalls->
13429 						    su_signal_oob)
13430 						    (connp->conn_upper_handle,
13431 						    urp);
13432 					}
13433 				} else {
13434 					mp1 = allocb(0, BPRI_MED);
13435 					if (mp1 == NULL) {
13436 						freemsg(mp);
13437 						return;
13438 					}
13439 					if (!TCP_IS_DETACHED(tcp) &&
13440 					    !putnextctl1(tcp->tcp_rq,
13441 					    M_PCSIG, SIGURG)) {
13442 						/* Try again on the rexmit. */
13443 						freemsg(mp1);
13444 						freemsg(mp);
13445 						return;
13446 					}
13447 					/*
13448 					 * If the next byte would be the mark
13449 					 * then mark with MARKNEXT else mark
13450 					 * with NOTMARKNEXT.
13451 					 */
13452 					if (gap == 0 && urp == 0)
13453 						mp1->b_flag |= MSGMARKNEXT;
13454 					else
13455 						mp1->b_flag |= MSGNOTMARKNEXT;
13456 					freemsg(tcp->tcp_urp_mark_mp);
13457 					tcp->tcp_urp_mark_mp = mp1;
13458 					flags |= TH_SEND_URP_MARK;
13459 				}
13460 				tcp->tcp_urp_last_valid = B_TRUE;
13461 				tcp->tcp_urp_last = urp + seg_seq;
13462 			}
13463 			/*
13464 			 * If this is a zero window probe, continue to
13465 			 * process the ACK part.  But we need to set seg_len
13466 			 * to 0 to avoid data processing.  Otherwise just
13467 			 * drop the segment and send back an ACK.
13468 			 */
13469 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13470 				flags &= ~(TH_SYN | TH_URG);
13471 				seg_len = 0;
13472 				goto process_ack;
13473 			} else {
13474 				freemsg(mp);
13475 				goto ack_check;
13476 			}
13477 		}
13478 		/* Pitch out of window stuff off the end. */
13479 		rgap = seg_len;
13480 		mp2 = mp;
13481 		do {
13482 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13483 			    (uintptr_t)INT_MAX);
13484 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13485 			if (rgap < 0) {
13486 				mp2->b_wptr += rgap;
13487 				if ((mp1 = mp2->b_cont) != NULL) {
13488 					mp2->b_cont = NULL;
13489 					freemsg(mp1);
13490 				}
13491 				break;
13492 			}
13493 		} while ((mp2 = mp2->b_cont) != NULL);
13494 	}
13495 ok:;
13496 	/*
13497 	 * TCP should check ECN info for segments inside the window only.
13498 	 * Therefore the check should be done here.
13499 	 */
13500 	if (tcp->tcp_ecn_ok) {
13501 		if (flags & TH_CWR) {
13502 			tcp->tcp_ecn_echo_on = B_FALSE;
13503 		}
13504 		/*
13505 		 * Note that both ECN_CE and CWR can be set in the
13506 		 * same segment.  In this case, we once again turn
13507 		 * on ECN_ECHO.
13508 		 */
13509 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13510 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13511 
13512 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13513 				tcp->tcp_ecn_echo_on = B_TRUE;
13514 			}
13515 		} else {
13516 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13517 
13518 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13519 			    htonl(IPH_ECN_CE << 20)) {
13520 				tcp->tcp_ecn_echo_on = B_TRUE;
13521 			}
13522 		}
13523 	}
13524 
13525 	/*
13526 	 * Check whether we can update tcp_ts_recent.  This test is
13527 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13528 	 * Extensions for High Performance: An Update", Internet Draft.
13529 	 */
13530 	if (tcp->tcp_snd_ts_ok &&
13531 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13532 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13533 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13534 		tcp->tcp_last_rcv_lbolt = lbolt64;
13535 	}
13536 
13537 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13538 		/*
13539 		 * FIN in an out of order segment.  We record this in
13540 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13541 		 * Clear the FIN so that any check on FIN flag will fail.
13542 		 * Remember that FIN also counts in the sequence number
13543 		 * space.  So we need to ack out of order FIN only segments.
13544 		 */
13545 		if (flags & TH_FIN) {
13546 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13547 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13548 			flags &= ~TH_FIN;
13549 			flags |= TH_ACK_NEEDED;
13550 		}
13551 		if (seg_len > 0) {
13552 			/* Fill in the SACK blk list. */
13553 			if (tcp->tcp_snd_sack_ok) {
13554 				ASSERT(tcp->tcp_sack_info != NULL);
13555 				tcp_sack_insert(tcp->tcp_sack_list,
13556 				    seg_seq, seg_seq + seg_len,
13557 				    &(tcp->tcp_num_sack_blk));
13558 			}
13559 
13560 			/*
13561 			 * Attempt reassembly and see if we have something
13562 			 * ready to go.
13563 			 */
13564 			mp = tcp_reass(tcp, mp, seg_seq);
13565 			/* Always ack out of order packets */
13566 			flags |= TH_ACK_NEEDED | TH_PUSH;
13567 			if (mp) {
13568 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13569 				    (uintptr_t)INT_MAX);
13570 				seg_len = mp->b_cont ? msgdsize(mp) :
13571 				    (int)(mp->b_wptr - mp->b_rptr);
13572 				seg_seq = tcp->tcp_rnxt;
13573 				/*
13574 				 * A gap is filled and the seq num and len
13575 				 * of the gap match that of a previously
13576 				 * received FIN, put the FIN flag back in.
13577 				 */
13578 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13579 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13580 					flags |= TH_FIN;
13581 					tcp->tcp_valid_bits &=
13582 					    ~TCP_OFO_FIN_VALID;
13583 				}
13584 			} else {
13585 				/*
13586 				 * Keep going even with NULL mp.
13587 				 * There may be a useful ACK or something else
13588 				 * we don't want to miss.
13589 				 *
13590 				 * But TCP should not perform fast retransmit
13591 				 * because of the ack number.  TCP uses
13592 				 * seg_len == 0 to determine if it is a pure
13593 				 * ACK.  And this is not a pure ACK.
13594 				 */
13595 				seg_len = 0;
13596 				ofo_seg = B_TRUE;
13597 			}
13598 		}
13599 	} else if (seg_len > 0) {
13600 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13601 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13602 		/*
13603 		 * If an out of order FIN was received before, and the seq
13604 		 * num and len of the new segment match that of the FIN,
13605 		 * put the FIN flag back in.
13606 		 */
13607 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13608 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13609 			flags |= TH_FIN;
13610 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13611 		}
13612 	}
13613 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13614 	if (flags & TH_RST) {
13615 		freemsg(mp);
13616 		switch (tcp->tcp_state) {
13617 		case TCPS_SYN_RCVD:
13618 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13619 			break;
13620 		case TCPS_ESTABLISHED:
13621 		case TCPS_FIN_WAIT_1:
13622 		case TCPS_FIN_WAIT_2:
13623 		case TCPS_CLOSE_WAIT:
13624 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13625 			break;
13626 		case TCPS_CLOSING:
13627 		case TCPS_LAST_ACK:
13628 			(void) tcp_clean_death(tcp, 0, 16);
13629 			break;
13630 		default:
13631 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13632 			(void) tcp_clean_death(tcp, ENXIO, 17);
13633 			break;
13634 		}
13635 		return;
13636 	}
13637 	if (flags & TH_SYN) {
13638 		/*
13639 		 * See RFC 793, Page 71
13640 		 *
13641 		 * The seq number must be in the window as it should
13642 		 * be "fixed" above.  If it is outside window, it should
13643 		 * be already rejected.  Note that we allow seg_seq to be
13644 		 * rnxt + rwnd because we want to accept 0 window probe.
13645 		 */
13646 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13647 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13648 		freemsg(mp);
13649 		/*
13650 		 * If the ACK flag is not set, just use our snxt as the
13651 		 * seq number of the RST segment.
13652 		 */
13653 		if (!(flags & TH_ACK)) {
13654 			seg_ack = tcp->tcp_snxt;
13655 		}
13656 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13657 		    TH_RST|TH_ACK);
13658 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13659 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13660 		return;
13661 	}
13662 	/*
13663 	 * urp could be -1 when the urp field in the packet is 0
13664 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13665 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13666 	 */
13667 	if (flags & TH_URG && urp >= 0) {
13668 		if (!tcp->tcp_urp_last_valid ||
13669 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13670 			/*
13671 			 * Non-STREAMS sockets handle the urgent data a litte
13672 			 * differently from STREAMS based sockets. There is no
13673 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
13674 			 * flags to keep SIOCATMARK happy. Instead a
13675 			 * su_signal_oob upcall is made to update the mark.
13676 			 * Neither is a T_EXDATA_IND mblk needed to be
13677 			 * prepended to the urgent data. The urgent data is
13678 			 * delivered using the su_recv upcall, where we set
13679 			 * the MSG_OOB flag to indicate that it is urg data.
13680 			 *
13681 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
13682 			 * are used by non-STREAMS sockets.
13683 			 */
13684 			if (IPCL_IS_NONSTR(connp)) {
13685 				if (!TCP_IS_DETACHED(tcp)) {
13686 					(*connp->conn_upcalls->su_signal_oob)
13687 					    (connp->conn_upper_handle, urp);
13688 				}
13689 			} else {
13690 				/*
13691 				 * If we haven't generated the signal yet for
13692 				 * this urgent pointer value, do it now.  Also,
13693 				 * send up a zero-length M_DATA indicating
13694 				 * whether or not this is the mark. The latter
13695 				 * is not needed when a T_EXDATA_IND is sent up.
13696 				 * However, if there are allocation failures
13697 				 * this code relies on the sender retransmitting
13698 				 * and the socket code for determining the mark
13699 				 * should not block waiting for the peer to
13700 				 * transmit. Thus, for simplicity we always
13701 				 * send up the mark indication.
13702 				 */
13703 				mp1 = allocb(0, BPRI_MED);
13704 				if (mp1 == NULL) {
13705 					freemsg(mp);
13706 					return;
13707 				}
13708 				if (!TCP_IS_DETACHED(tcp) &&
13709 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13710 				    SIGURG)) {
13711 					/* Try again on the rexmit. */
13712 					freemsg(mp1);
13713 					freemsg(mp);
13714 					return;
13715 				}
13716 				/*
13717 				 * Mark with NOTMARKNEXT for now.
13718 				 * The code below will change this to MARKNEXT
13719 				 * if we are at the mark.
13720 				 *
13721 				 * If there are allocation failures (e.g. in
13722 				 * dupmsg below) the next time tcp_rput_data
13723 				 * sees the urgent segment it will send up the
13724 				 * MSGMARKNEXT message.
13725 				 */
13726 				mp1->b_flag |= MSGNOTMARKNEXT;
13727 				freemsg(tcp->tcp_urp_mark_mp);
13728 				tcp->tcp_urp_mark_mp = mp1;
13729 				flags |= TH_SEND_URP_MARK;
13730 #ifdef DEBUG
13731 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13732 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13733 				    "last %x, %s",
13734 				    seg_seq, urp, tcp->tcp_urp_last,
13735 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13736 #endif /* DEBUG */
13737 			}
13738 			tcp->tcp_urp_last_valid = B_TRUE;
13739 			tcp->tcp_urp_last = urp + seg_seq;
13740 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13741 			/*
13742 			 * An allocation failure prevented the previous
13743 			 * tcp_rput_data from sending up the allocated
13744 			 * MSG*MARKNEXT message - send it up this time
13745 			 * around.
13746 			 */
13747 			flags |= TH_SEND_URP_MARK;
13748 		}
13749 
13750 		/*
13751 		 * If the urgent byte is in this segment, make sure that it is
13752 		 * all by itself.  This makes it much easier to deal with the
13753 		 * possibility of an allocation failure on the T_exdata_ind.
13754 		 * Note that seg_len is the number of bytes in the segment, and
13755 		 * urp is the offset into the segment of the urgent byte.
13756 		 * urp < seg_len means that the urgent byte is in this segment.
13757 		 */
13758 		if (urp < seg_len) {
13759 			if (seg_len != 1) {
13760 				uint32_t  tmp_rnxt;
13761 				/*
13762 				 * Break it up and feed it back in.
13763 				 * Re-attach the IP header.
13764 				 */
13765 				mp->b_rptr = iphdr;
13766 				if (urp > 0) {
13767 					/*
13768 					 * There is stuff before the urgent
13769 					 * byte.
13770 					 */
13771 					mp1 = dupmsg(mp);
13772 					if (!mp1) {
13773 						/*
13774 						 * Trim from urgent byte on.
13775 						 * The rest will come back.
13776 						 */
13777 						(void) adjmsg(mp,
13778 						    urp - seg_len);
13779 						tcp_rput_data(connp,
13780 						    mp, NULL);
13781 						return;
13782 					}
13783 					(void) adjmsg(mp1, urp - seg_len);
13784 					/* Feed this piece back in. */
13785 					tmp_rnxt = tcp->tcp_rnxt;
13786 					tcp_rput_data(connp, mp1, NULL);
13787 					/*
13788 					 * If the data passed back in was not
13789 					 * processed (ie: bad ACK) sending
13790 					 * the remainder back in will cause a
13791 					 * loop. In this case, drop the
13792 					 * packet and let the sender try
13793 					 * sending a good packet.
13794 					 */
13795 					if (tmp_rnxt == tcp->tcp_rnxt) {
13796 						freemsg(mp);
13797 						return;
13798 					}
13799 				}
13800 				if (urp != seg_len - 1) {
13801 					uint32_t  tmp_rnxt;
13802 					/*
13803 					 * There is stuff after the urgent
13804 					 * byte.
13805 					 */
13806 					mp1 = dupmsg(mp);
13807 					if (!mp1) {
13808 						/*
13809 						 * Trim everything beyond the
13810 						 * urgent byte.  The rest will
13811 						 * come back.
13812 						 */
13813 						(void) adjmsg(mp,
13814 						    urp + 1 - seg_len);
13815 						tcp_rput_data(connp,
13816 						    mp, NULL);
13817 						return;
13818 					}
13819 					(void) adjmsg(mp1, urp + 1 - seg_len);
13820 					tmp_rnxt = tcp->tcp_rnxt;
13821 					tcp_rput_data(connp, mp1, NULL);
13822 					/*
13823 					 * If the data passed back in was not
13824 					 * processed (ie: bad ACK) sending
13825 					 * the remainder back in will cause a
13826 					 * loop. In this case, drop the
13827 					 * packet and let the sender try
13828 					 * sending a good packet.
13829 					 */
13830 					if (tmp_rnxt == tcp->tcp_rnxt) {
13831 						freemsg(mp);
13832 						return;
13833 					}
13834 				}
13835 				tcp_rput_data(connp, mp, NULL);
13836 				return;
13837 			}
13838 			/*
13839 			 * This segment contains only the urgent byte.  We
13840 			 * have to allocate the T_exdata_ind, if we can.
13841 			 */
13842 			if (IPCL_IS_NONSTR(connp)) {
13843 				int error;
13844 
13845 				(*connp->conn_upcalls->su_recv)
13846 				    (connp->conn_upper_handle, mp, seg_len,
13847 				    MSG_OOB, &error, NULL);
13848 				/*
13849 				 * We should never be in middle of a
13850 				 * fallback, the squeue guarantees that.
13851 				 */
13852 				ASSERT(error != EOPNOTSUPP);
13853 				mp = NULL;
13854 				goto update_ack;
13855 			} else if (!tcp->tcp_urp_mp) {
13856 				struct T_exdata_ind *tei;
13857 				mp1 = allocb(sizeof (struct T_exdata_ind),
13858 				    BPRI_MED);
13859 				if (!mp1) {
13860 					/*
13861 					 * Sigh... It'll be back.
13862 					 * Generate any MSG*MARK message now.
13863 					 */
13864 					freemsg(mp);
13865 					seg_len = 0;
13866 					if (flags & TH_SEND_URP_MARK) {
13867 
13868 
13869 						ASSERT(tcp->tcp_urp_mark_mp);
13870 						tcp->tcp_urp_mark_mp->b_flag &=
13871 						    ~MSGNOTMARKNEXT;
13872 						tcp->tcp_urp_mark_mp->b_flag |=
13873 						    MSGMARKNEXT;
13874 					}
13875 					goto ack_check;
13876 				}
13877 				mp1->b_datap->db_type = M_PROTO;
13878 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13879 				tei->PRIM_type = T_EXDATA_IND;
13880 				tei->MORE_flag = 0;
13881 				mp1->b_wptr = (uchar_t *)&tei[1];
13882 				tcp->tcp_urp_mp = mp1;
13883 #ifdef DEBUG
13884 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13885 				    "tcp_rput: allocated exdata_ind %s",
13886 				    tcp_display(tcp, NULL,
13887 				    DISP_PORT_ONLY));
13888 #endif /* DEBUG */
13889 				/*
13890 				 * There is no need to send a separate MSG*MARK
13891 				 * message since the T_EXDATA_IND will be sent
13892 				 * now.
13893 				 */
13894 				flags &= ~TH_SEND_URP_MARK;
13895 				freemsg(tcp->tcp_urp_mark_mp);
13896 				tcp->tcp_urp_mark_mp = NULL;
13897 			}
13898 			/*
13899 			 * Now we are all set.  On the next putnext upstream,
13900 			 * tcp_urp_mp will be non-NULL and will get prepended
13901 			 * to what has to be this piece containing the urgent
13902 			 * byte.  If for any reason we abort this segment below,
13903 			 * if it comes back, we will have this ready, or it
13904 			 * will get blown off in close.
13905 			 */
13906 		} else if (urp == seg_len) {
13907 			/*
13908 			 * The urgent byte is the next byte after this sequence
13909 			 * number. If this endpoint is non-STREAMS, then there
13910 			 * is nothing to do here since the socket has already
13911 			 * been notified about the urg pointer by the
13912 			 * su_signal_oob call above.
13913 			 *
13914 			 * In case of STREAMS, some more work might be needed.
13915 			 * If there is data it is marked with MSGMARKNEXT and
13916 			 * and any tcp_urp_mark_mp is discarded since it is not
13917 			 * needed. Otherwise, if the code above just allocated
13918 			 * a zero-length tcp_urp_mark_mp message, that message
13919 			 * is tagged with MSGMARKNEXT. Sending up these
13920 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
13921 			 * even though the T_EXDATA_IND will not be sent up
13922 			 * until the urgent byte arrives.
13923 			 */
13924 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
13925 				if (seg_len != 0) {
13926 					flags |= TH_MARKNEXT_NEEDED;
13927 					freemsg(tcp->tcp_urp_mark_mp);
13928 					tcp->tcp_urp_mark_mp = NULL;
13929 					flags &= ~TH_SEND_URP_MARK;
13930 				} else if (tcp->tcp_urp_mark_mp != NULL) {
13931 					flags |= TH_SEND_URP_MARK;
13932 					tcp->tcp_urp_mark_mp->b_flag &=
13933 					    ~MSGNOTMARKNEXT;
13934 					tcp->tcp_urp_mark_mp->b_flag |=
13935 					    MSGMARKNEXT;
13936 				}
13937 			}
13938 #ifdef DEBUG
13939 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13940 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13941 			    seg_len, flags,
13942 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13943 #endif /* DEBUG */
13944 		}
13945 #ifdef DEBUG
13946 		else {
13947 			/* Data left until we hit mark */
13948 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13949 			    "tcp_rput: URP %d bytes left, %s",
13950 			    urp - seg_len, tcp_display(tcp, NULL,
13951 			    DISP_PORT_ONLY));
13952 		}
13953 #endif /* DEBUG */
13954 	}
13955 
13956 process_ack:
13957 	if (!(flags & TH_ACK)) {
13958 		freemsg(mp);
13959 		goto xmit_check;
13960 	}
13961 	}
13962 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13963 
13964 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13965 		tcp->tcp_ip_forward_progress = B_TRUE;
13966 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13967 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13968 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13969 			/* 3-way handshake complete - pass up the T_CONN_IND */
13970 			tcp_t	*listener = tcp->tcp_listener;
13971 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13972 
13973 			tcp->tcp_tconnind_started = B_TRUE;
13974 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13975 			/*
13976 			 * We are here means eager is fine but it can
13977 			 * get a TH_RST at any point between now and till
13978 			 * accept completes and disappear. We need to
13979 			 * ensure that reference to eager is valid after
13980 			 * we get out of eager's perimeter. So we do
13981 			 * an extra refhold.
13982 			 */
13983 			CONN_INC_REF(connp);
13984 
13985 			/*
13986 			 * The listener also exists because of the refhold
13987 			 * done in tcp_conn_request. Its possible that it
13988 			 * might have closed. We will check that once we
13989 			 * get inside listeners context.
13990 			 */
13991 			CONN_INC_REF(listener->tcp_connp);
13992 			if (listener->tcp_connp->conn_sqp ==
13993 			    connp->conn_sqp) {
13994 				/*
13995 				 * We optimize by not calling an SQUEUE_ENTER
13996 				 * on the listener since we know that the
13997 				 * listener and eager squeues are the same.
13998 				 * We are able to make this check safely only
13999 				 * because neither the eager nor the listener
14000 				 * can change its squeue. Only an active connect
14001 				 * can change its squeue
14002 				 */
14003 				tcp_send_conn_ind(listener->tcp_connp, mp,
14004 				    listener->tcp_connp->conn_sqp);
14005 				CONN_DEC_REF(listener->tcp_connp);
14006 			} else if (!tcp->tcp_loopback) {
14007 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14008 				    mp, tcp_send_conn_ind,
14009 				    listener->tcp_connp, SQ_FILL,
14010 				    SQTAG_TCP_CONN_IND);
14011 			} else {
14012 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14013 				    mp, tcp_send_conn_ind,
14014 				    listener->tcp_connp, SQ_PROCESS,
14015 				    SQTAG_TCP_CONN_IND);
14016 			}
14017 		}
14018 
14019 		/*
14020 		 * We are seeing the final ack in the three way
14021 		 * hand shake of a active open'ed connection
14022 		 * so we must send up a T_CONN_CON
14023 		 *
14024 		 * tcp_sendmsg() checks tcp_state without entering
14025 		 * the squeue so tcp_state should be updated before
14026 		 * sending up connection confirmation.
14027 		 */
14028 		tcp->tcp_state = TCPS_ESTABLISHED;
14029 		if (tcp->tcp_active_open) {
14030 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14031 				freemsg(mp);
14032 				tcp->tcp_state = TCPS_SYN_RCVD;
14033 				return;
14034 			}
14035 			/*
14036 			 * Don't fuse the loopback endpoints for
14037 			 * simultaneous active opens.
14038 			 */
14039 			if (tcp->tcp_loopback) {
14040 				TCP_STAT(tcps, tcp_fusion_unfusable);
14041 				tcp->tcp_unfusable = B_TRUE;
14042 			}
14043 		}
14044 
14045 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14046 		bytes_acked--;
14047 		/* SYN was acked - making progress */
14048 		if (tcp->tcp_ipversion == IPV6_VERSION)
14049 			tcp->tcp_ip_forward_progress = B_TRUE;
14050 
14051 		/*
14052 		 * If SYN was retransmitted, need to reset all
14053 		 * retransmission info as this segment will be
14054 		 * treated as a dup ACK.
14055 		 */
14056 		if (tcp->tcp_rexmit) {
14057 			tcp->tcp_rexmit = B_FALSE;
14058 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14059 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14060 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14061 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14062 			tcp->tcp_ms_we_have_waited = 0;
14063 			tcp->tcp_cwnd = mss;
14064 		}
14065 
14066 		/*
14067 		 * We set the send window to zero here.
14068 		 * This is needed if there is data to be
14069 		 * processed already on the queue.
14070 		 * Later (at swnd_update label), the
14071 		 * "new_swnd > tcp_swnd" condition is satisfied
14072 		 * the XMIT_NEEDED flag is set in the current
14073 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14074 		 * called if there is already data on queue in
14075 		 * this state.
14076 		 */
14077 		tcp->tcp_swnd = 0;
14078 
14079 		if (new_swnd > tcp->tcp_max_swnd)
14080 			tcp->tcp_max_swnd = new_swnd;
14081 		tcp->tcp_swl1 = seg_seq;
14082 		tcp->tcp_swl2 = seg_ack;
14083 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14084 
14085 		/* Fuse when both sides are in ESTABLISHED state */
14086 		if (tcp->tcp_loopback && do_tcp_fusion)
14087 			tcp_fuse(tcp, iphdr, tcph);
14088 
14089 	}
14090 	/* This code follows 4.4BSD-Lite2 mostly. */
14091 	if (bytes_acked < 0)
14092 		goto est;
14093 
14094 	/*
14095 	 * If TCP is ECN capable and the congestion experience bit is
14096 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14097 	 * done once per window (or more loosely, per RTT).
14098 	 */
14099 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14100 		tcp->tcp_cwr = B_FALSE;
14101 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14102 		if (!tcp->tcp_cwr) {
14103 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14104 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14105 			tcp->tcp_cwnd = npkt * mss;
14106 			/*
14107 			 * If the cwnd is 0, use the timer to clock out
14108 			 * new segments.  This is required by the ECN spec.
14109 			 */
14110 			if (npkt == 0) {
14111 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14112 				/*
14113 				 * This makes sure that when the ACK comes
14114 				 * back, we will increase tcp_cwnd by 1 MSS.
14115 				 */
14116 				tcp->tcp_cwnd_cnt = 0;
14117 			}
14118 			tcp->tcp_cwr = B_TRUE;
14119 			/*
14120 			 * This marks the end of the current window of in
14121 			 * flight data.  That is why we don't use
14122 			 * tcp_suna + tcp_swnd.  Only data in flight can
14123 			 * provide ECN info.
14124 			 */
14125 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14126 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14127 		}
14128 	}
14129 
14130 	mp1 = tcp->tcp_xmit_head;
14131 	if (bytes_acked == 0) {
14132 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14133 			int dupack_cnt;
14134 
14135 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14136 			/*
14137 			 * Fast retransmit.  When we have seen exactly three
14138 			 * identical ACKs while we have unacked data
14139 			 * outstanding we take it as a hint that our peer
14140 			 * dropped something.
14141 			 *
14142 			 * If TCP is retransmitting, don't do fast retransmit.
14143 			 */
14144 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14145 			    ! tcp->tcp_rexmit) {
14146 				/* Do Limited Transmit */
14147 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14148 				    tcps->tcps_dupack_fast_retransmit) {
14149 					/*
14150 					 * RFC 3042
14151 					 *
14152 					 * What we need to do is temporarily
14153 					 * increase tcp_cwnd so that new
14154 					 * data can be sent if it is allowed
14155 					 * by the receive window (tcp_rwnd).
14156 					 * tcp_wput_data() will take care of
14157 					 * the rest.
14158 					 *
14159 					 * If the connection is SACK capable,
14160 					 * only do limited xmit when there
14161 					 * is SACK info.
14162 					 *
14163 					 * Note how tcp_cwnd is incremented.
14164 					 * The first dup ACK will increase
14165 					 * it by 1 MSS.  The second dup ACK
14166 					 * will increase it by 2 MSS.  This
14167 					 * means that only 1 new segment will
14168 					 * be sent for each dup ACK.
14169 					 */
14170 					if (tcp->tcp_unsent > 0 &&
14171 					    (!tcp->tcp_snd_sack_ok ||
14172 					    (tcp->tcp_snd_sack_ok &&
14173 					    tcp->tcp_notsack_list != NULL))) {
14174 						tcp->tcp_cwnd += mss <<
14175 						    (tcp->tcp_dupack_cnt - 1);
14176 						flags |= TH_LIMIT_XMIT;
14177 					}
14178 				} else if (dupack_cnt ==
14179 				    tcps->tcps_dupack_fast_retransmit) {
14180 
14181 				/*
14182 				 * If we have reduced tcp_ssthresh
14183 				 * because of ECN, do not reduce it again
14184 				 * unless it is already one window of data
14185 				 * away.  After one window of data, tcp_cwr
14186 				 * should then be cleared.  Note that
14187 				 * for non ECN capable connection, tcp_cwr
14188 				 * should always be false.
14189 				 *
14190 				 * Adjust cwnd since the duplicate
14191 				 * ack indicates that a packet was
14192 				 * dropped (due to congestion.)
14193 				 */
14194 				if (!tcp->tcp_cwr) {
14195 					npkt = ((tcp->tcp_snxt -
14196 					    tcp->tcp_suna) >> 1) / mss;
14197 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14198 					    mss;
14199 					tcp->tcp_cwnd = (npkt +
14200 					    tcp->tcp_dupack_cnt) * mss;
14201 				}
14202 				if (tcp->tcp_ecn_ok) {
14203 					tcp->tcp_cwr = B_TRUE;
14204 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14205 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14206 				}
14207 
14208 				/*
14209 				 * We do Hoe's algorithm.  Refer to her
14210 				 * paper "Improving the Start-up Behavior
14211 				 * of a Congestion Control Scheme for TCP,"
14212 				 * appeared in SIGCOMM'96.
14213 				 *
14214 				 * Save highest seq no we have sent so far.
14215 				 * Be careful about the invisible FIN byte.
14216 				 */
14217 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14218 				    (tcp->tcp_unsent == 0)) {
14219 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14220 				} else {
14221 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14222 				}
14223 
14224 				/*
14225 				 * Do not allow bursty traffic during.
14226 				 * fast recovery.  Refer to Fall and Floyd's
14227 				 * paper "Simulation-based Comparisons of
14228 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14229 				 * This is a best current practise.
14230 				 */
14231 				tcp->tcp_snd_burst = TCP_CWND_SS;
14232 
14233 				/*
14234 				 * For SACK:
14235 				 * Calculate tcp_pipe, which is the
14236 				 * estimated number of bytes in
14237 				 * network.
14238 				 *
14239 				 * tcp_fack is the highest sack'ed seq num
14240 				 * TCP has received.
14241 				 *
14242 				 * tcp_pipe is explained in the above quoted
14243 				 * Fall and Floyd's paper.  tcp_fack is
14244 				 * explained in Mathis and Mahdavi's
14245 				 * "Forward Acknowledgment: Refining TCP
14246 				 * Congestion Control" in SIGCOMM '96.
14247 				 */
14248 				if (tcp->tcp_snd_sack_ok) {
14249 					ASSERT(tcp->tcp_sack_info != NULL);
14250 					if (tcp->tcp_notsack_list != NULL) {
14251 						tcp->tcp_pipe = tcp->tcp_snxt -
14252 						    tcp->tcp_fack;
14253 						tcp->tcp_sack_snxt = seg_ack;
14254 						flags |= TH_NEED_SACK_REXMIT;
14255 					} else {
14256 						/*
14257 						 * Always initialize tcp_pipe
14258 						 * even though we don't have
14259 						 * any SACK info.  If later
14260 						 * we get SACK info and
14261 						 * tcp_pipe is not initialized,
14262 						 * funny things will happen.
14263 						 */
14264 						tcp->tcp_pipe =
14265 						    tcp->tcp_cwnd_ssthresh;
14266 					}
14267 				} else {
14268 					flags |= TH_REXMIT_NEEDED;
14269 				} /* tcp_snd_sack_ok */
14270 
14271 				} else {
14272 					/*
14273 					 * Here we perform congestion
14274 					 * avoidance, but NOT slow start.
14275 					 * This is known as the Fast
14276 					 * Recovery Algorithm.
14277 					 */
14278 					if (tcp->tcp_snd_sack_ok &&
14279 					    tcp->tcp_notsack_list != NULL) {
14280 						flags |= TH_NEED_SACK_REXMIT;
14281 						tcp->tcp_pipe -= mss;
14282 						if (tcp->tcp_pipe < 0)
14283 							tcp->tcp_pipe = 0;
14284 					} else {
14285 					/*
14286 					 * We know that one more packet has
14287 					 * left the pipe thus we can update
14288 					 * cwnd.
14289 					 */
14290 					cwnd = tcp->tcp_cwnd + mss;
14291 					if (cwnd > tcp->tcp_cwnd_max)
14292 						cwnd = tcp->tcp_cwnd_max;
14293 					tcp->tcp_cwnd = cwnd;
14294 					if (tcp->tcp_unsent > 0)
14295 						flags |= TH_XMIT_NEEDED;
14296 					}
14297 				}
14298 			}
14299 		} else if (tcp->tcp_zero_win_probe) {
14300 			/*
14301 			 * If the window has opened, need to arrange
14302 			 * to send additional data.
14303 			 */
14304 			if (new_swnd != 0) {
14305 				/* tcp_suna != tcp_snxt */
14306 				/* Packet contains a window update */
14307 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14308 				tcp->tcp_zero_win_probe = 0;
14309 				tcp->tcp_timer_backoff = 0;
14310 				tcp->tcp_ms_we_have_waited = 0;
14311 
14312 				/*
14313 				 * Transmit starting with tcp_suna since
14314 				 * the one byte probe is not ack'ed.
14315 				 * If TCP has sent more than one identical
14316 				 * probe, tcp_rexmit will be set.  That means
14317 				 * tcp_ss_rexmit() will send out the one
14318 				 * byte along with new data.  Otherwise,
14319 				 * fake the retransmission.
14320 				 */
14321 				flags |= TH_XMIT_NEEDED;
14322 				if (!tcp->tcp_rexmit) {
14323 					tcp->tcp_rexmit = B_TRUE;
14324 					tcp->tcp_dupack_cnt = 0;
14325 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14326 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14327 				}
14328 			}
14329 		}
14330 		goto swnd_update;
14331 	}
14332 
14333 	/*
14334 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14335 	 * If the ACK value acks something that we have not yet sent, it might
14336 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14337 	 * other side.
14338 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14339 	 * state is handled above, so we can always just drop the segment and
14340 	 * send an ACK here.
14341 	 *
14342 	 * In the case where the peer shrinks the window, we see the new window
14343 	 * update, but all the data sent previously is queued up by the peer.
14344 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
14345 	 * number, which was already sent, and within window, is recorded.
14346 	 * tcp_snxt is then updated.
14347 	 *
14348 	 * If the window has previously shrunk, and an ACK for data not yet
14349 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
14350 	 * the ACK is for data within the window at the time the window was
14351 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
14352 	 * the sequence number ACK'ed.
14353 	 *
14354 	 * If the ACK covers all the data sent at the time the window was
14355 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
14356 	 *
14357 	 * Should we send ACKs in response to ACK only segments?
14358 	 */
14359 
14360 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14361 		if ((tcp->tcp_is_wnd_shrnk) &&
14362 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
14363 			uint32_t data_acked_ahead_snxt;
14364 
14365 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
14366 			tcp_update_xmit_tail(tcp, seg_ack);
14367 			tcp->tcp_unsent -= data_acked_ahead_snxt;
14368 		} else {
14369 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14370 			/* drop the received segment */
14371 			freemsg(mp);
14372 
14373 			/*
14374 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14375 			 * greater than 0, check if the number of such
14376 			 * bogus ACks is greater than that count.  If yes,
14377 			 * don't send back any ACK.  This prevents TCP from
14378 			 * getting into an ACK storm if somehow an attacker
14379 			 * successfully spoofs an acceptable segment to our
14380 			 * peer.
14381 			 */
14382 			if (tcp_drop_ack_unsent_cnt > 0 &&
14383 			    ++tcp->tcp_in_ack_unsent >
14384 			    tcp_drop_ack_unsent_cnt) {
14385 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14386 				return;
14387 			}
14388 			mp = tcp_ack_mp(tcp);
14389 			if (mp != NULL) {
14390 				BUMP_LOCAL(tcp->tcp_obsegs);
14391 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14392 				tcp_send_data(tcp, tcp->tcp_wq, mp);
14393 			}
14394 			return;
14395 		}
14396 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
14397 	    tcp->tcp_snxt_shrunk)) {
14398 			tcp->tcp_is_wnd_shrnk = B_FALSE;
14399 	}
14400 
14401 	/*
14402 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14403 	 * blocks that are covered by this ACK.
14404 	 */
14405 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14406 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14407 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14408 	}
14409 
14410 	/*
14411 	 * If we got an ACK after fast retransmit, check to see
14412 	 * if it is a partial ACK.  If it is not and the congestion
14413 	 * window was inflated to account for the other side's
14414 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14415 	 */
14416 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14417 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14418 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14419 			tcp->tcp_dupack_cnt = 0;
14420 			/*
14421 			 * Restore the orig tcp_cwnd_ssthresh after
14422 			 * fast retransmit phase.
14423 			 */
14424 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14425 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14426 			}
14427 			tcp->tcp_rexmit_max = seg_ack;
14428 			tcp->tcp_cwnd_cnt = 0;
14429 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14430 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14431 
14432 			/*
14433 			 * Remove all notsack info to avoid confusion with
14434 			 * the next fast retrasnmit/recovery phase.
14435 			 */
14436 			if (tcp->tcp_snd_sack_ok &&
14437 			    tcp->tcp_notsack_list != NULL) {
14438 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
14439 				    tcp);
14440 			}
14441 		} else {
14442 			if (tcp->tcp_snd_sack_ok &&
14443 			    tcp->tcp_notsack_list != NULL) {
14444 				flags |= TH_NEED_SACK_REXMIT;
14445 				tcp->tcp_pipe -= mss;
14446 				if (tcp->tcp_pipe < 0)
14447 					tcp->tcp_pipe = 0;
14448 			} else {
14449 				/*
14450 				 * Hoe's algorithm:
14451 				 *
14452 				 * Retransmit the unack'ed segment and
14453 				 * restart fast recovery.  Note that we
14454 				 * need to scale back tcp_cwnd to the
14455 				 * original value when we started fast
14456 				 * recovery.  This is to prevent overly
14457 				 * aggressive behaviour in sending new
14458 				 * segments.
14459 				 */
14460 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14461 				    tcps->tcps_dupack_fast_retransmit * mss;
14462 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14463 				flags |= TH_REXMIT_NEEDED;
14464 			}
14465 		}
14466 	} else {
14467 		tcp->tcp_dupack_cnt = 0;
14468 		if (tcp->tcp_rexmit) {
14469 			/*
14470 			 * TCP is retranmitting.  If the ACK ack's all
14471 			 * outstanding data, update tcp_rexmit_max and
14472 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14473 			 * to the correct value.
14474 			 *
14475 			 * Note that SEQ_LEQ() is used.  This is to avoid
14476 			 * unnecessary fast retransmit caused by dup ACKs
14477 			 * received when TCP does slow start retransmission
14478 			 * after a time out.  During this phase, TCP may
14479 			 * send out segments which are already received.
14480 			 * This causes dup ACKs to be sent back.
14481 			 */
14482 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14483 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14484 					tcp->tcp_rexmit_nxt = seg_ack;
14485 				}
14486 				if (seg_ack != tcp->tcp_rexmit_max) {
14487 					flags |= TH_XMIT_NEEDED;
14488 				}
14489 			} else {
14490 				tcp->tcp_rexmit = B_FALSE;
14491 				tcp->tcp_xmit_zc_clean = B_FALSE;
14492 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14493 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14494 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14495 			}
14496 			tcp->tcp_ms_we_have_waited = 0;
14497 		}
14498 	}
14499 
14500 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14501 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14502 	tcp->tcp_suna = seg_ack;
14503 	if (tcp->tcp_zero_win_probe != 0) {
14504 		tcp->tcp_zero_win_probe = 0;
14505 		tcp->tcp_timer_backoff = 0;
14506 	}
14507 
14508 	/*
14509 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14510 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14511 	 * will not reach here.
14512 	 */
14513 	if (mp1 == NULL) {
14514 		goto fin_acked;
14515 	}
14516 
14517 	/*
14518 	 * Update the congestion window.
14519 	 *
14520 	 * If TCP is not ECN capable or TCP is ECN capable but the
14521 	 * congestion experience bit is not set, increase the tcp_cwnd as
14522 	 * usual.
14523 	 */
14524 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14525 		cwnd = tcp->tcp_cwnd;
14526 		add = mss;
14527 
14528 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14529 			/*
14530 			 * This is to prevent an increase of less than 1 MSS of
14531 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14532 			 * may send out tinygrams in order to preserve mblk
14533 			 * boundaries.
14534 			 *
14535 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14536 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14537 			 * increased by 1 MSS for every RTTs.
14538 			 */
14539 			if (tcp->tcp_cwnd_cnt <= 0) {
14540 				tcp->tcp_cwnd_cnt = cwnd + add;
14541 			} else {
14542 				tcp->tcp_cwnd_cnt -= add;
14543 				add = 0;
14544 			}
14545 		}
14546 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14547 	}
14548 
14549 	/* See if the latest urgent data has been acknowledged */
14550 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14551 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14552 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14553 
14554 	/* Can we update the RTT estimates? */
14555 	if (tcp->tcp_snd_ts_ok) {
14556 		/* Ignore zero timestamp echo-reply. */
14557 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14558 			tcp_set_rto(tcp, (int32_t)lbolt -
14559 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14560 		}
14561 
14562 		/* If needed, restart the timer. */
14563 		if (tcp->tcp_set_timer == 1) {
14564 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14565 			tcp->tcp_set_timer = 0;
14566 		}
14567 		/*
14568 		 * Update tcp_csuna in case the other side stops sending
14569 		 * us timestamps.
14570 		 */
14571 		tcp->tcp_csuna = tcp->tcp_snxt;
14572 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14573 		/*
14574 		 * An ACK sequence we haven't seen before, so get the RTT
14575 		 * and update the RTO. But first check if the timestamp is
14576 		 * valid to use.
14577 		 */
14578 		if ((mp1->b_next != NULL) &&
14579 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14580 			tcp_set_rto(tcp, (int32_t)lbolt -
14581 			    (int32_t)(intptr_t)mp1->b_prev);
14582 		else
14583 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14584 
14585 		/* Remeber the last sequence to be ACKed */
14586 		tcp->tcp_csuna = seg_ack;
14587 		if (tcp->tcp_set_timer == 1) {
14588 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14589 			tcp->tcp_set_timer = 0;
14590 		}
14591 	} else {
14592 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14593 	}
14594 
14595 	/* Eat acknowledged bytes off the xmit queue. */
14596 	for (;;) {
14597 		mblk_t	*mp2;
14598 		uchar_t	*wptr;
14599 
14600 		wptr = mp1->b_wptr;
14601 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14602 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14603 		if (bytes_acked < 0) {
14604 			mp1->b_rptr = wptr + bytes_acked;
14605 			/*
14606 			 * Set a new timestamp if all the bytes timed by the
14607 			 * old timestamp have been ack'ed.
14608 			 */
14609 			if (SEQ_GT(seg_ack,
14610 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14611 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14612 				mp1->b_next = NULL;
14613 			}
14614 			break;
14615 		}
14616 		mp1->b_next = NULL;
14617 		mp1->b_prev = NULL;
14618 		mp2 = mp1;
14619 		mp1 = mp1->b_cont;
14620 
14621 		/*
14622 		 * This notification is required for some zero-copy
14623 		 * clients to maintain a copy semantic. After the data
14624 		 * is ack'ed, client is safe to modify or reuse the buffer.
14625 		 */
14626 		if (tcp->tcp_snd_zcopy_aware &&
14627 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14628 			tcp_zcopy_notify(tcp);
14629 		freeb(mp2);
14630 		if (bytes_acked == 0) {
14631 			if (mp1 == NULL) {
14632 				/* Everything is ack'ed, clear the tail. */
14633 				tcp->tcp_xmit_tail = NULL;
14634 				/*
14635 				 * Cancel the timer unless we are still
14636 				 * waiting for an ACK for the FIN packet.
14637 				 */
14638 				if (tcp->tcp_timer_tid != 0 &&
14639 				    tcp->tcp_snxt == tcp->tcp_suna) {
14640 					(void) TCP_TIMER_CANCEL(tcp,
14641 					    tcp->tcp_timer_tid);
14642 					tcp->tcp_timer_tid = 0;
14643 				}
14644 				goto pre_swnd_update;
14645 			}
14646 			if (mp2 != tcp->tcp_xmit_tail)
14647 				break;
14648 			tcp->tcp_xmit_tail = mp1;
14649 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14650 			    (uintptr_t)INT_MAX);
14651 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14652 			    mp1->b_rptr);
14653 			break;
14654 		}
14655 		if (mp1 == NULL) {
14656 			/*
14657 			 * More was acked but there is nothing more
14658 			 * outstanding.  This means that the FIN was
14659 			 * just acked or that we're talking to a clown.
14660 			 */
14661 fin_acked:
14662 			ASSERT(tcp->tcp_fin_sent);
14663 			tcp->tcp_xmit_tail = NULL;
14664 			if (tcp->tcp_fin_sent) {
14665 				/* FIN was acked - making progress */
14666 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14667 				    !tcp->tcp_fin_acked)
14668 					tcp->tcp_ip_forward_progress = B_TRUE;
14669 				tcp->tcp_fin_acked = B_TRUE;
14670 				if (tcp->tcp_linger_tid != 0 &&
14671 				    TCP_TIMER_CANCEL(tcp,
14672 				    tcp->tcp_linger_tid) >= 0) {
14673 					tcp_stop_lingering(tcp);
14674 					freemsg(mp);
14675 					mp = NULL;
14676 				}
14677 			} else {
14678 				/*
14679 				 * We should never get here because
14680 				 * we have already checked that the
14681 				 * number of bytes ack'ed should be
14682 				 * smaller than or equal to what we
14683 				 * have sent so far (it is the
14684 				 * acceptability check of the ACK).
14685 				 * We can only get here if the send
14686 				 * queue is corrupted.
14687 				 *
14688 				 * Terminate the connection and
14689 				 * panic the system.  It is better
14690 				 * for us to panic instead of
14691 				 * continuing to avoid other disaster.
14692 				 */
14693 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14694 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14695 				panic("Memory corruption "
14696 				    "detected for connection %s.",
14697 				    tcp_display(tcp, NULL,
14698 				    DISP_ADDR_AND_PORT));
14699 				/*NOTREACHED*/
14700 			}
14701 			goto pre_swnd_update;
14702 		}
14703 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14704 	}
14705 	if (tcp->tcp_unsent) {
14706 		flags |= TH_XMIT_NEEDED;
14707 	}
14708 pre_swnd_update:
14709 	tcp->tcp_xmit_head = mp1;
14710 swnd_update:
14711 	/*
14712 	 * The following check is different from most other implementations.
14713 	 * For bi-directional transfer, when segments are dropped, the
14714 	 * "normal" check will not accept a window update in those
14715 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14716 	 * segments which are outside receiver's window.  As TCP accepts
14717 	 * the ack in those retransmitted segments, if the window update in
14718 	 * the same segment is not accepted, TCP will incorrectly calculates
14719 	 * that it can send more segments.  This can create a deadlock
14720 	 * with the receiver if its window becomes zero.
14721 	 */
14722 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14723 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14724 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14725 		/*
14726 		 * The criteria for update is:
14727 		 *
14728 		 * 1. the segment acknowledges some data.  Or
14729 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14730 		 * 3. the segment is not old and the advertised window is
14731 		 * larger than the previous advertised window.
14732 		 */
14733 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14734 			flags |= TH_XMIT_NEEDED;
14735 		tcp->tcp_swnd = new_swnd;
14736 		if (new_swnd > tcp->tcp_max_swnd)
14737 			tcp->tcp_max_swnd = new_swnd;
14738 		tcp->tcp_swl1 = seg_seq;
14739 		tcp->tcp_swl2 = seg_ack;
14740 	}
14741 est:
14742 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14743 
14744 		switch (tcp->tcp_state) {
14745 		case TCPS_FIN_WAIT_1:
14746 			if (tcp->tcp_fin_acked) {
14747 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14748 				/*
14749 				 * We implement the non-standard BSD/SunOS
14750 				 * FIN_WAIT_2 flushing algorithm.
14751 				 * If there is no user attached to this
14752 				 * TCP endpoint, then this TCP struct
14753 				 * could hang around forever in FIN_WAIT_2
14754 				 * state if the peer forgets to send us
14755 				 * a FIN.  To prevent this, we wait only
14756 				 * 2*MSL (a convenient time value) for
14757 				 * the FIN to arrive.  If it doesn't show up,
14758 				 * we flush the TCP endpoint.  This algorithm,
14759 				 * though a violation of RFC-793, has worked
14760 				 * for over 10 years in BSD systems.
14761 				 * Note: SunOS 4.x waits 675 seconds before
14762 				 * flushing the FIN_WAIT_2 connection.
14763 				 */
14764 				TCP_TIMER_RESTART(tcp,
14765 				    tcps->tcps_fin_wait_2_flush_interval);
14766 			}
14767 			break;
14768 		case TCPS_FIN_WAIT_2:
14769 			break;	/* Shutdown hook? */
14770 		case TCPS_LAST_ACK:
14771 			freemsg(mp);
14772 			if (tcp->tcp_fin_acked) {
14773 				(void) tcp_clean_death(tcp, 0, 19);
14774 				return;
14775 			}
14776 			goto xmit_check;
14777 		case TCPS_CLOSING:
14778 			if (tcp->tcp_fin_acked) {
14779 				tcp->tcp_state = TCPS_TIME_WAIT;
14780 				/*
14781 				 * Unconditionally clear the exclusive binding
14782 				 * bit so this TIME-WAIT connection won't
14783 				 * interfere with new ones.
14784 				 */
14785 				tcp->tcp_exclbind = 0;
14786 				if (!TCP_IS_DETACHED(tcp)) {
14787 					TCP_TIMER_RESTART(tcp,
14788 					    tcps->tcps_time_wait_interval);
14789 				} else {
14790 					tcp_time_wait_append(tcp);
14791 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14792 				}
14793 			}
14794 			/*FALLTHRU*/
14795 		case TCPS_CLOSE_WAIT:
14796 			freemsg(mp);
14797 			goto xmit_check;
14798 		default:
14799 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14800 			break;
14801 		}
14802 	}
14803 	if (flags & TH_FIN) {
14804 		/* Make sure we ack the fin */
14805 		flags |= TH_ACK_NEEDED;
14806 		if (!tcp->tcp_fin_rcvd) {
14807 			tcp->tcp_fin_rcvd = B_TRUE;
14808 			tcp->tcp_rnxt++;
14809 			tcph = tcp->tcp_tcph;
14810 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14811 
14812 			/*
14813 			 * Generate the ordrel_ind at the end unless we
14814 			 * are an eager guy.
14815 			 * In the eager case tcp_rsrv will do this when run
14816 			 * after tcp_accept is done.
14817 			 */
14818 			if (tcp->tcp_listener == NULL &&
14819 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14820 				flags |= TH_ORDREL_NEEDED;
14821 			switch (tcp->tcp_state) {
14822 			case TCPS_SYN_RCVD:
14823 			case TCPS_ESTABLISHED:
14824 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14825 				/* Keepalive? */
14826 				break;
14827 			case TCPS_FIN_WAIT_1:
14828 				if (!tcp->tcp_fin_acked) {
14829 					tcp->tcp_state = TCPS_CLOSING;
14830 					break;
14831 				}
14832 				/* FALLTHRU */
14833 			case TCPS_FIN_WAIT_2:
14834 				tcp->tcp_state = TCPS_TIME_WAIT;
14835 				/*
14836 				 * Unconditionally clear the exclusive binding
14837 				 * bit so this TIME-WAIT connection won't
14838 				 * interfere with new ones.
14839 				 */
14840 				tcp->tcp_exclbind = 0;
14841 				if (!TCP_IS_DETACHED(tcp)) {
14842 					TCP_TIMER_RESTART(tcp,
14843 					    tcps->tcps_time_wait_interval);
14844 				} else {
14845 					tcp_time_wait_append(tcp);
14846 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14847 				}
14848 				if (seg_len) {
14849 					/*
14850 					 * implies data piggybacked on FIN.
14851 					 * break to handle data.
14852 					 */
14853 					break;
14854 				}
14855 				freemsg(mp);
14856 				goto ack_check;
14857 			}
14858 		}
14859 	}
14860 	if (mp == NULL)
14861 		goto xmit_check;
14862 	if (seg_len == 0) {
14863 		freemsg(mp);
14864 		goto xmit_check;
14865 	}
14866 	if (mp->b_rptr == mp->b_wptr) {
14867 		/*
14868 		 * The header has been consumed, so we remove the
14869 		 * zero-length mblk here.
14870 		 */
14871 		mp1 = mp;
14872 		mp = mp->b_cont;
14873 		freeb(mp1);
14874 	}
14875 update_ack:
14876 	tcph = tcp->tcp_tcph;
14877 	tcp->tcp_rack_cnt++;
14878 	{
14879 		uint32_t cur_max;
14880 
14881 		cur_max = tcp->tcp_rack_cur_max;
14882 		if (tcp->tcp_rack_cnt >= cur_max) {
14883 			/*
14884 			 * We have more unacked data than we should - send
14885 			 * an ACK now.
14886 			 */
14887 			flags |= TH_ACK_NEEDED;
14888 			cur_max++;
14889 			if (cur_max > tcp->tcp_rack_abs_max)
14890 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14891 			else
14892 				tcp->tcp_rack_cur_max = cur_max;
14893 		} else if (TCP_IS_DETACHED(tcp)) {
14894 			/* We don't have an ACK timer for detached TCP. */
14895 			flags |= TH_ACK_NEEDED;
14896 		} else if (seg_len < mss) {
14897 			/*
14898 			 * If we get a segment that is less than an mss, and we
14899 			 * already have unacknowledged data, and the amount
14900 			 * unacknowledged is not a multiple of mss, then we
14901 			 * better generate an ACK now.  Otherwise, this may be
14902 			 * the tail piece of a transaction, and we would rather
14903 			 * wait for the response.
14904 			 */
14905 			uint32_t udif;
14906 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14907 			    (uintptr_t)INT_MAX);
14908 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14909 			if (udif && (udif % mss))
14910 				flags |= TH_ACK_NEEDED;
14911 			else
14912 				flags |= TH_ACK_TIMER_NEEDED;
14913 		} else {
14914 			/* Start delayed ack timer */
14915 			flags |= TH_ACK_TIMER_NEEDED;
14916 		}
14917 	}
14918 	tcp->tcp_rnxt += seg_len;
14919 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14920 
14921 	if (mp == NULL)
14922 		goto xmit_check;
14923 
14924 	/* Update SACK list */
14925 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14926 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14927 		    &(tcp->tcp_num_sack_blk));
14928 	}
14929 
14930 	if (tcp->tcp_urp_mp) {
14931 		tcp->tcp_urp_mp->b_cont = mp;
14932 		mp = tcp->tcp_urp_mp;
14933 		tcp->tcp_urp_mp = NULL;
14934 		/* Ready for a new signal. */
14935 		tcp->tcp_urp_last_valid = B_FALSE;
14936 #ifdef DEBUG
14937 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14938 		    "tcp_rput: sending exdata_ind %s",
14939 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14940 #endif /* DEBUG */
14941 	}
14942 
14943 	/*
14944 	 * Check for ancillary data changes compared to last segment.
14945 	 */
14946 	if (tcp->tcp_ipv6_recvancillary != 0) {
14947 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14948 		ASSERT(mp != NULL);
14949 	}
14950 
14951 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14952 		/*
14953 		 * Side queue inbound data until the accept happens.
14954 		 * tcp_accept/tcp_rput drains this when the accept happens.
14955 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14956 		 * T_EXDATA_IND) it is queued on b_next.
14957 		 * XXX Make urgent data use this. Requires:
14958 		 *	Removing tcp_listener check for TH_URG
14959 		 *	Making M_PCPROTO and MARK messages skip the eager case
14960 		 */
14961 
14962 		if (tcp->tcp_kssl_pending) {
14963 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
14964 			    mblk_t *, mp);
14965 			tcp_kssl_input(tcp, mp);
14966 		} else {
14967 			tcp_rcv_enqueue(tcp, mp, seg_len);
14968 		}
14969 	} else if (IPCL_IS_NONSTR(connp)) {
14970 		/*
14971 		 * Non-STREAMS socket
14972 		 *
14973 		 * Note that no KSSL processing is done here, because
14974 		 * KSSL is not supported for non-STREAMS sockets.
14975 		 */
14976 		boolean_t push = flags & (TH_PUSH|TH_FIN);
14977 		int error;
14978 
14979 		if ((*connp->conn_upcalls->su_recv)(
14980 		    connp->conn_upper_handle,
14981 		    mp, seg_len, 0, &error, &push) <= 0) {
14982 			/*
14983 			 * We should never be in middle of a
14984 			 * fallback, the squeue guarantees that.
14985 			 */
14986 			ASSERT(error != EOPNOTSUPP);
14987 			if (error == ENOSPC)
14988 				tcp->tcp_rwnd -= seg_len;
14989 		} else if (push) {
14990 			/* PUSH bit set and sockfs is not flow controlled */
14991 			flags |= tcp_rwnd_reopen(tcp);
14992 		}
14993 	} else {
14994 		/* STREAMS socket */
14995 		if (mp->b_datap->db_type != M_DATA ||
14996 		    (flags & TH_MARKNEXT_NEEDED)) {
14997 			if (tcp->tcp_rcv_list != NULL) {
14998 				flags |= tcp_rcv_drain(tcp);
14999 			}
15000 			ASSERT(tcp->tcp_rcv_list == NULL ||
15001 			    tcp->tcp_fused_sigurg);
15002 
15003 			if (flags & TH_MARKNEXT_NEEDED) {
15004 #ifdef DEBUG
15005 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15006 				    "tcp_rput: sending MSGMARKNEXT %s",
15007 				    tcp_display(tcp, NULL,
15008 				    DISP_PORT_ONLY));
15009 #endif /* DEBUG */
15010 				mp->b_flag |= MSGMARKNEXT;
15011 				flags &= ~TH_MARKNEXT_NEEDED;
15012 			}
15013 
15014 			/* Does this need SSL processing first? */
15015 			if ((tcp->tcp_kssl_ctx != NULL) &&
15016 			    (DB_TYPE(mp) == M_DATA)) {
15017 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15018 				    mblk_t *, mp);
15019 				tcp_kssl_input(tcp, mp);
15020 			} else {
15021 				putnext(tcp->tcp_rq, mp);
15022 				if (!canputnext(tcp->tcp_rq))
15023 					tcp->tcp_rwnd -= seg_len;
15024 			}
15025 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15026 		    (DB_TYPE(mp) == M_DATA)) {
15027 			/* Does this need SSL processing first? */
15028 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15029 			tcp_kssl_input(tcp, mp);
15030 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15031 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15032 			if (tcp->tcp_rcv_list != NULL) {
15033 				/*
15034 				 * Enqueue the new segment first and then
15035 				 * call tcp_rcv_drain() to send all data
15036 				 * up.  The other way to do this is to
15037 				 * send all queued data up and then call
15038 				 * putnext() to send the new segment up.
15039 				 * This way can remove the else part later
15040 				 * on.
15041 				 *
15042 				 * We don't do this to avoid one more call to
15043 				 * canputnext() as tcp_rcv_drain() needs to
15044 				 * call canputnext().
15045 				 */
15046 				tcp_rcv_enqueue(tcp, mp, seg_len);
15047 				flags |= tcp_rcv_drain(tcp);
15048 			} else {
15049 				putnext(tcp->tcp_rq, mp);
15050 				if (!canputnext(tcp->tcp_rq))
15051 					tcp->tcp_rwnd -= seg_len;
15052 			}
15053 		} else {
15054 			/*
15055 			 * Enqueue all packets when processing an mblk
15056 			 * from the co queue and also enqueue normal packets.
15057 			 */
15058 			tcp_rcv_enqueue(tcp, mp, seg_len);
15059 		}
15060 		/*
15061 		 * Make sure the timer is running if we have data waiting
15062 		 * for a push bit. This provides resiliency against
15063 		 * implementations that do not correctly generate push bits.
15064 		 */
15065 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
15066 			/*
15067 			 * The connection may be closed at this point, so don't
15068 			 * do anything for a detached tcp.
15069 			 */
15070 			if (!TCP_IS_DETACHED(tcp))
15071 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15072 				    tcp_push_timer,
15073 				    MSEC_TO_TICK(
15074 				    tcps->tcps_push_timer_interval));
15075 		}
15076 	}
15077 
15078 xmit_check:
15079 	/* Is there anything left to do? */
15080 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15081 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15082 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15083 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15084 		goto done;
15085 
15086 	/* Any transmit work to do and a non-zero window? */
15087 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15088 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15089 		if (flags & TH_REXMIT_NEEDED) {
15090 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15091 
15092 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15093 			if (snd_size > mss)
15094 				snd_size = mss;
15095 			if (snd_size > tcp->tcp_swnd)
15096 				snd_size = tcp->tcp_swnd;
15097 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15098 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15099 			    B_TRUE);
15100 
15101 			if (mp1 != NULL) {
15102 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15103 				tcp->tcp_csuna = tcp->tcp_snxt;
15104 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15105 				UPDATE_MIB(&tcps->tcps_mib,
15106 				    tcpRetransBytes, snd_size);
15107 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15108 			}
15109 		}
15110 		if (flags & TH_NEED_SACK_REXMIT) {
15111 			tcp_sack_rxmit(tcp, &flags);
15112 		}
15113 		/*
15114 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15115 		 * out new segment.  Note that tcp_rexmit should not be
15116 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15117 		 */
15118 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15119 			if (!tcp->tcp_rexmit) {
15120 				tcp_wput_data(tcp, NULL, B_FALSE);
15121 			} else {
15122 				tcp_ss_rexmit(tcp);
15123 			}
15124 		}
15125 		/*
15126 		 * Adjust tcp_cwnd back to normal value after sending
15127 		 * new data segments.
15128 		 */
15129 		if (flags & TH_LIMIT_XMIT) {
15130 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15131 			/*
15132 			 * This will restart the timer.  Restarting the
15133 			 * timer is used to avoid a timeout before the
15134 			 * limited transmitted segment's ACK gets back.
15135 			 */
15136 			if (tcp->tcp_xmit_head != NULL)
15137 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15138 		}
15139 
15140 		/* Anything more to do? */
15141 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15142 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15143 			goto done;
15144 	}
15145 ack_check:
15146 	if (flags & TH_SEND_URP_MARK) {
15147 		ASSERT(tcp->tcp_urp_mark_mp);
15148 		ASSERT(!IPCL_IS_NONSTR(connp));
15149 		/*
15150 		 * Send up any queued data and then send the mark message
15151 		 */
15152 		if (tcp->tcp_rcv_list != NULL) {
15153 			flags |= tcp_rcv_drain(tcp);
15154 
15155 		}
15156 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15157 		mp1 = tcp->tcp_urp_mark_mp;
15158 		tcp->tcp_urp_mark_mp = NULL;
15159 		putnext(tcp->tcp_rq, mp1);
15160 #ifdef DEBUG
15161 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15162 		    "tcp_rput: sending zero-length %s %s",
15163 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15164 		    "MSGNOTMARKNEXT"),
15165 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15166 #endif /* DEBUG */
15167 		flags &= ~TH_SEND_URP_MARK;
15168 	}
15169 	if (flags & TH_ACK_NEEDED) {
15170 		/*
15171 		 * Time to send an ack for some reason.
15172 		 */
15173 		mp1 = tcp_ack_mp(tcp);
15174 
15175 		if (mp1 != NULL) {
15176 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15177 			BUMP_LOCAL(tcp->tcp_obsegs);
15178 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15179 		}
15180 		if (tcp->tcp_ack_tid != 0) {
15181 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15182 			tcp->tcp_ack_tid = 0;
15183 		}
15184 	}
15185 	if (flags & TH_ACK_TIMER_NEEDED) {
15186 		/*
15187 		 * Arrange for deferred ACK or push wait timeout.
15188 		 * Start timer if it is not already running.
15189 		 */
15190 		if (tcp->tcp_ack_tid == 0) {
15191 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15192 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15193 			    (clock_t)tcps->tcps_local_dack_interval :
15194 			    (clock_t)tcps->tcps_deferred_ack_interval));
15195 		}
15196 	}
15197 	if (flags & TH_ORDREL_NEEDED) {
15198 		/*
15199 		 * Send up the ordrel_ind unless we are an eager guy.
15200 		 * In the eager case tcp_rsrv will do this when run
15201 		 * after tcp_accept is done.
15202 		 */
15203 		ASSERT(tcp->tcp_listener == NULL);
15204 
15205 		if (IPCL_IS_NONSTR(connp)) {
15206 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15207 			tcp->tcp_ordrel_done = B_TRUE;
15208 			(*connp->conn_upcalls->su_opctl)
15209 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15210 			goto done;
15211 		}
15212 
15213 		if (tcp->tcp_rcv_list != NULL) {
15214 			/*
15215 			 * Push any mblk(s) enqueued from co processing.
15216 			 */
15217 			flags |= tcp_rcv_drain(tcp);
15218 		}
15219 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15220 
15221 		mp1 = tcp->tcp_ordrel_mp;
15222 		tcp->tcp_ordrel_mp = NULL;
15223 		tcp->tcp_ordrel_done = B_TRUE;
15224 		putnext(tcp->tcp_rq, mp1);
15225 	}
15226 done:
15227 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15228 }
15229 
15230 /*
15231  * This routine adjusts next-to-send sequence number variables, in the
15232  * case where the reciever has shrunk it's window.
15233  */
15234 static void
15235 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
15236 {
15237 	mblk_t *xmit_tail;
15238 	int32_t offset;
15239 
15240 	tcp->tcp_snxt = snxt;
15241 
15242 	/* Get the mblk, and the offset in it, as per the shrunk window */
15243 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
15244 	ASSERT(xmit_tail != NULL);
15245 	tcp->tcp_xmit_tail = xmit_tail;
15246 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
15247 	    xmit_tail->b_rptr - offset;
15248 }
15249 
15250 /*
15251  * This function does PAWS protection check. Returns B_TRUE if the
15252  * segment passes the PAWS test, else returns B_FALSE.
15253  */
15254 boolean_t
15255 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15256 {
15257 	uint8_t	flags;
15258 	int	options;
15259 	uint8_t *up;
15260 
15261 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15262 	/*
15263 	 * If timestamp option is aligned nicely, get values inline,
15264 	 * otherwise call general routine to parse.  Only do that
15265 	 * if timestamp is the only option.
15266 	 */
15267 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15268 	    TCPOPT_REAL_TS_LEN &&
15269 	    OK_32PTR((up = ((uint8_t *)tcph) +
15270 	    TCP_MIN_HEADER_LENGTH)) &&
15271 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15272 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15273 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15274 
15275 		options = TCP_OPT_TSTAMP_PRESENT;
15276 	} else {
15277 		if (tcp->tcp_snd_sack_ok) {
15278 			tcpoptp->tcp = tcp;
15279 		} else {
15280 			tcpoptp->tcp = NULL;
15281 		}
15282 		options = tcp_parse_options(tcph, tcpoptp);
15283 	}
15284 
15285 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15286 		/*
15287 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15288 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15289 		 */
15290 		if ((flags & TH_RST) == 0 &&
15291 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15292 		    tcp->tcp_ts_recent)) {
15293 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15294 			    PAWS_TIMEOUT)) {
15295 				/* This segment is not acceptable. */
15296 				return (B_FALSE);
15297 			} else {
15298 				/*
15299 				 * Connection has been idle for
15300 				 * too long.  Reset the timestamp
15301 				 * and assume the segment is valid.
15302 				 */
15303 				tcp->tcp_ts_recent =
15304 				    tcpoptp->tcp_opt_ts_val;
15305 			}
15306 		}
15307 	} else {
15308 		/*
15309 		 * If we don't get a timestamp on every packet, we
15310 		 * figure we can't really trust 'em, so we stop sending
15311 		 * and parsing them.
15312 		 */
15313 		tcp->tcp_snd_ts_ok = B_FALSE;
15314 
15315 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15316 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15317 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15318 		/*
15319 		 * Adjust the tcp_mss accordingly. We also need to
15320 		 * adjust tcp_cwnd here in accordance with the new mss.
15321 		 * But we avoid doing a slow start here so as to not
15322 		 * to lose on the transfer rate built up so far.
15323 		 */
15324 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15325 		if (tcp->tcp_snd_sack_ok) {
15326 			ASSERT(tcp->tcp_sack_info != NULL);
15327 			tcp->tcp_max_sack_blk = 4;
15328 		}
15329 	}
15330 	return (B_TRUE);
15331 }
15332 
15333 /*
15334  * Attach ancillary data to a received TCP segments for the
15335  * ancillary pieces requested by the application that are
15336  * different than they were in the previous data segment.
15337  *
15338  * Save the "current" values once memory allocation is ok so that
15339  * when memory allocation fails we can just wait for the next data segment.
15340  */
15341 static mblk_t *
15342 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15343 {
15344 	struct T_optdata_ind *todi;
15345 	int optlen;
15346 	uchar_t *optptr;
15347 	struct T_opthdr *toh;
15348 	uint_t addflag;	/* Which pieces to add */
15349 	mblk_t *mp1;
15350 
15351 	optlen = 0;
15352 	addflag = 0;
15353 	/* If app asked for pktinfo and the index has changed ... */
15354 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15355 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15356 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15357 		optlen += sizeof (struct T_opthdr) +
15358 		    sizeof (struct in6_pktinfo);
15359 		addflag |= TCP_IPV6_RECVPKTINFO;
15360 	}
15361 	/* If app asked for hoplimit and it has changed ... */
15362 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15363 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15364 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15365 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15366 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15367 	}
15368 	/* If app asked for tclass and it has changed ... */
15369 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15370 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15371 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15372 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15373 		addflag |= TCP_IPV6_RECVTCLASS;
15374 	}
15375 	/*
15376 	 * If app asked for hopbyhop headers and it has changed ...
15377 	 * For security labels, note that (1) security labels can't change on
15378 	 * a connected socket at all, (2) we're connected to at most one peer,
15379 	 * (3) if anything changes, then it must be some other extra option.
15380 	 */
15381 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15382 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15383 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15384 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15385 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15386 		    tcp->tcp_label_len;
15387 		addflag |= TCP_IPV6_RECVHOPOPTS;
15388 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15389 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15390 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15391 			return (mp);
15392 	}
15393 	/* If app asked for dst headers before routing headers ... */
15394 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15395 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15396 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15397 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15398 		optlen += sizeof (struct T_opthdr) +
15399 		    ipp->ipp_rtdstoptslen;
15400 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15401 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15402 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15403 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15404 			return (mp);
15405 	}
15406 	/* If app asked for routing headers and it has changed ... */
15407 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15408 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15409 	    (ipp->ipp_fields & IPPF_RTHDR),
15410 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15411 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15412 		addflag |= TCP_IPV6_RECVRTHDR;
15413 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15414 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15415 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15416 			return (mp);
15417 	}
15418 	/* If app asked for dest headers and it has changed ... */
15419 	if ((tcp->tcp_ipv6_recvancillary &
15420 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15421 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15422 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15423 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15424 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15425 		addflag |= TCP_IPV6_RECVDSTOPTS;
15426 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15427 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15428 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15429 			return (mp);
15430 	}
15431 
15432 	if (optlen == 0) {
15433 		/* Nothing to add */
15434 		return (mp);
15435 	}
15436 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15437 	if (mp1 == NULL) {
15438 		/*
15439 		 * Defer sending ancillary data until the next TCP segment
15440 		 * arrives.
15441 		 */
15442 		return (mp);
15443 	}
15444 	mp1->b_cont = mp;
15445 	mp = mp1;
15446 	mp->b_wptr += sizeof (*todi) + optlen;
15447 	mp->b_datap->db_type = M_PROTO;
15448 	todi = (struct T_optdata_ind *)mp->b_rptr;
15449 	todi->PRIM_type = T_OPTDATA_IND;
15450 	todi->DATA_flag = 1;	/* MORE data */
15451 	todi->OPT_length = optlen;
15452 	todi->OPT_offset = sizeof (*todi);
15453 	optptr = (uchar_t *)&todi[1];
15454 	/*
15455 	 * If app asked for pktinfo and the index has changed ...
15456 	 * Note that the local address never changes for the connection.
15457 	 */
15458 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15459 		struct in6_pktinfo *pkti;
15460 
15461 		toh = (struct T_opthdr *)optptr;
15462 		toh->level = IPPROTO_IPV6;
15463 		toh->name = IPV6_PKTINFO;
15464 		toh->len = sizeof (*toh) + sizeof (*pkti);
15465 		toh->status = 0;
15466 		optptr += sizeof (*toh);
15467 		pkti = (struct in6_pktinfo *)optptr;
15468 		if (tcp->tcp_ipversion == IPV6_VERSION)
15469 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15470 		else
15471 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15472 			    &pkti->ipi6_addr);
15473 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15474 		optptr += sizeof (*pkti);
15475 		ASSERT(OK_32PTR(optptr));
15476 		/* Save as "last" value */
15477 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15478 	}
15479 	/* If app asked for hoplimit and it has changed ... */
15480 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15481 		toh = (struct T_opthdr *)optptr;
15482 		toh->level = IPPROTO_IPV6;
15483 		toh->name = IPV6_HOPLIMIT;
15484 		toh->len = sizeof (*toh) + sizeof (uint_t);
15485 		toh->status = 0;
15486 		optptr += sizeof (*toh);
15487 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15488 		optptr += sizeof (uint_t);
15489 		ASSERT(OK_32PTR(optptr));
15490 		/* Save as "last" value */
15491 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15492 	}
15493 	/* If app asked for tclass and it has changed ... */
15494 	if (addflag & TCP_IPV6_RECVTCLASS) {
15495 		toh = (struct T_opthdr *)optptr;
15496 		toh->level = IPPROTO_IPV6;
15497 		toh->name = IPV6_TCLASS;
15498 		toh->len = sizeof (*toh) + sizeof (uint_t);
15499 		toh->status = 0;
15500 		optptr += sizeof (*toh);
15501 		*(uint_t *)optptr = ipp->ipp_tclass;
15502 		optptr += sizeof (uint_t);
15503 		ASSERT(OK_32PTR(optptr));
15504 		/* Save as "last" value */
15505 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15506 	}
15507 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15508 		toh = (struct T_opthdr *)optptr;
15509 		toh->level = IPPROTO_IPV6;
15510 		toh->name = IPV6_HOPOPTS;
15511 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15512 		    tcp->tcp_label_len;
15513 		toh->status = 0;
15514 		optptr += sizeof (*toh);
15515 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15516 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15517 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15518 		ASSERT(OK_32PTR(optptr));
15519 		/* Save as last value */
15520 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15521 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15522 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15523 	}
15524 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15525 		toh = (struct T_opthdr *)optptr;
15526 		toh->level = IPPROTO_IPV6;
15527 		toh->name = IPV6_RTHDRDSTOPTS;
15528 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15529 		toh->status = 0;
15530 		optptr += sizeof (*toh);
15531 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15532 		optptr += ipp->ipp_rtdstoptslen;
15533 		ASSERT(OK_32PTR(optptr));
15534 		/* Save as last value */
15535 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15536 		    &tcp->tcp_rtdstoptslen,
15537 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15538 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15539 	}
15540 	if (addflag & TCP_IPV6_RECVRTHDR) {
15541 		toh = (struct T_opthdr *)optptr;
15542 		toh->level = IPPROTO_IPV6;
15543 		toh->name = IPV6_RTHDR;
15544 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15545 		toh->status = 0;
15546 		optptr += sizeof (*toh);
15547 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15548 		optptr += ipp->ipp_rthdrlen;
15549 		ASSERT(OK_32PTR(optptr));
15550 		/* Save as last value */
15551 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15552 		    (ipp->ipp_fields & IPPF_RTHDR),
15553 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15554 	}
15555 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15556 		toh = (struct T_opthdr *)optptr;
15557 		toh->level = IPPROTO_IPV6;
15558 		toh->name = IPV6_DSTOPTS;
15559 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15560 		toh->status = 0;
15561 		optptr += sizeof (*toh);
15562 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15563 		optptr += ipp->ipp_dstoptslen;
15564 		ASSERT(OK_32PTR(optptr));
15565 		/* Save as last value */
15566 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15567 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15568 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15569 	}
15570 	ASSERT(optptr == mp->b_wptr);
15571 	return (mp);
15572 }
15573 
15574 /*
15575  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15576  * messages.
15577  */
15578 void
15579 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15580 {
15581 	uchar_t	*rptr = mp->b_rptr;
15582 	queue_t	*q = tcp->tcp_rq;
15583 	struct T_error_ack *tea;
15584 
15585 	switch (mp->b_datap->db_type) {
15586 	case M_PROTO:
15587 	case M_PCPROTO:
15588 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15589 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15590 			break;
15591 		tea = (struct T_error_ack *)rptr;
15592 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15593 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15594 		    tea->ERROR_prim != T_BIND_REQ);
15595 		switch (tea->PRIM_type) {
15596 		case T_ERROR_ACK:
15597 			if (tcp->tcp_debug) {
15598 				(void) strlog(TCP_MOD_ID, 0, 1,
15599 				    SL_TRACE|SL_ERROR,
15600 				    "tcp_rput_other: case T_ERROR_ACK, "
15601 				    "ERROR_prim == %d",
15602 				    tea->ERROR_prim);
15603 			}
15604 			switch (tea->ERROR_prim) {
15605 			case T_SVR4_OPTMGMT_REQ:
15606 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15607 					/* T_OPTMGMT_REQ generated by TCP */
15608 					printf("T_SVR4_OPTMGMT_REQ failed "
15609 					    "%d/%d - dropped (cnt %d)\n",
15610 					    tea->TLI_error, tea->UNIX_error,
15611 					    tcp->tcp_drop_opt_ack_cnt);
15612 					freemsg(mp);
15613 					tcp->tcp_drop_opt_ack_cnt--;
15614 					return;
15615 				}
15616 				break;
15617 			}
15618 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15619 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15620 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15621 				    "- dropped (cnt %d)\n",
15622 				    tea->TLI_error, tea->UNIX_error,
15623 				    tcp->tcp_drop_opt_ack_cnt);
15624 				freemsg(mp);
15625 				tcp->tcp_drop_opt_ack_cnt--;
15626 				return;
15627 			}
15628 			break;
15629 		case T_OPTMGMT_ACK:
15630 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15631 				/* T_OPTMGMT_REQ generated by TCP */
15632 				freemsg(mp);
15633 				tcp->tcp_drop_opt_ack_cnt--;
15634 				return;
15635 			}
15636 			break;
15637 		default:
15638 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15639 			break;
15640 		}
15641 		break;
15642 	case M_FLUSH:
15643 		if (*rptr & FLUSHR)
15644 			flushq(q, FLUSHDATA);
15645 		break;
15646 	default:
15647 		/* M_CTL will be directly sent to tcp_icmp_error() */
15648 		ASSERT(DB_TYPE(mp) != M_CTL);
15649 		break;
15650 	}
15651 	/*
15652 	 * Make sure we set this bit before sending the ACK for
15653 	 * bind. Otherwise accept could possibly run and free
15654 	 * this tcp struct.
15655 	 */
15656 	ASSERT(q != NULL);
15657 	putnext(q, mp);
15658 }
15659 
15660 /* ARGSUSED */
15661 static void
15662 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15663 {
15664 	conn_t	*connp = (conn_t *)arg;
15665 	tcp_t	*tcp = connp->conn_tcp;
15666 	queue_t	*q = tcp->tcp_rq;
15667 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15668 
15669 	ASSERT(!IPCL_IS_NONSTR(connp));
15670 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15671 	tcp->tcp_rsrv_mp = mp;
15672 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15673 
15674 	TCP_STAT(tcps, tcp_rsrv_calls);
15675 
15676 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15677 		return;
15678 	}
15679 
15680 	if (tcp->tcp_fused) {
15681 		tcp_fuse_backenable(tcp);
15682 		return;
15683 	}
15684 
15685 	if (canputnext(q)) {
15686 		/* Not flow-controlled, open rwnd */
15687 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
15688 
15689 		/*
15690 		 * Send back a window update immediately if TCP is above
15691 		 * ESTABLISHED state and the increase of the rcv window
15692 		 * that the other side knows is at least 1 MSS after flow
15693 		 * control is lifted.
15694 		 */
15695 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15696 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
15697 			tcp_xmit_ctl(NULL, tcp,
15698 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15699 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15700 		}
15701 	}
15702 }
15703 
15704 /*
15705  * The read side service routine is called mostly when we get back-enabled as a
15706  * result of flow control relief.  Since we don't actually queue anything in
15707  * TCP, we have no data to send out of here.  What we do is clear the receive
15708  * window, and send out a window update.
15709  */
15710 static void
15711 tcp_rsrv(queue_t *q)
15712 {
15713 	conn_t		*connp = Q_TO_CONN(q);
15714 	tcp_t		*tcp = connp->conn_tcp;
15715 	mblk_t		*mp;
15716 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15717 
15718 	/* No code does a putq on the read side */
15719 	ASSERT(q->q_first == NULL);
15720 
15721 	/* Nothing to do for the default queue */
15722 	if (q == tcps->tcps_g_q) {
15723 		return;
15724 	}
15725 
15726 	/*
15727 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
15728 	 * been run.  So just return.
15729 	 */
15730 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15731 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
15732 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
15733 		return;
15734 	}
15735 	tcp->tcp_rsrv_mp = NULL;
15736 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15737 
15738 	CONN_INC_REF(connp);
15739 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15740 	    SQ_PROCESS, SQTAG_TCP_RSRV);
15741 }
15742 
15743 /*
15744  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15745  * We do not allow the receive window to shrink.  After setting rwnd,
15746  * set the flow control hiwat of the stream.
15747  *
15748  * This function is called in 2 cases:
15749  *
15750  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15751  *    connection (passive open) and in tcp_rput_data() for active connect.
15752  *    This is called after tcp_mss_set() when the desired MSS value is known.
15753  *    This makes sure that our window size is a mutiple of the other side's
15754  *    MSS.
15755  * 2) Handling SO_RCVBUF option.
15756  *
15757  * It is ASSUMED that the requested size is a multiple of the current MSS.
15758  *
15759  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15760  * user requests so.
15761  */
15762 int
15763 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15764 {
15765 	uint32_t	mss = tcp->tcp_mss;
15766 	uint32_t	old_max_rwnd;
15767 	uint32_t	max_transmittable_rwnd;
15768 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15769 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15770 
15771 	/*
15772 	 * Insist on a receive window that is at least
15773 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15774 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15775 	 * and delayed acknowledgement.
15776 	 */
15777 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
15778 
15779 	if (tcp->tcp_fused) {
15780 		size_t sth_hiwat;
15781 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15782 
15783 		ASSERT(peer_tcp != NULL);
15784 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15785 		if (!tcp_detached) {
15786 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
15787 			    sth_hiwat);
15788 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
15789 		}
15790 
15791 		/*
15792 		 * In the fusion case, the maxpsz stream head value of
15793 		 * our peer is set according to its send buffer size
15794 		 * and our receive buffer size; since the latter may
15795 		 * have changed we need to update the peer's maxpsz.
15796 		 */
15797 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15798 		return (sth_hiwat);
15799 	}
15800 
15801 	if (tcp_detached) {
15802 		old_max_rwnd = tcp->tcp_rwnd;
15803 	} else {
15804 		old_max_rwnd = tcp->tcp_recv_hiwater;
15805 	}
15806 
15807 
15808 	/*
15809 	 * If window size info has already been exchanged, TCP should not
15810 	 * shrink the window.  Shrinking window is doable if done carefully.
15811 	 * We may add that support later.  But so far there is not a real
15812 	 * need to do that.
15813 	 */
15814 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15815 		/* MSS may have changed, do a round up again. */
15816 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15817 	}
15818 
15819 	/*
15820 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15821 	 * can be applied even before the window scale option is decided.
15822 	 */
15823 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15824 	if (rwnd > max_transmittable_rwnd) {
15825 		rwnd = max_transmittable_rwnd -
15826 		    (max_transmittable_rwnd % mss);
15827 		if (rwnd < mss)
15828 			rwnd = max_transmittable_rwnd;
15829 		/*
15830 		 * If we're over the limit we may have to back down tcp_rwnd.
15831 		 * The increment below won't work for us. So we set all three
15832 		 * here and the increment below will have no effect.
15833 		 */
15834 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15835 	}
15836 	if (tcp->tcp_localnet) {
15837 		tcp->tcp_rack_abs_max =
15838 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
15839 	} else {
15840 		/*
15841 		 * For a remote host on a different subnet (through a router),
15842 		 * we ack every other packet to be conforming to RFC1122.
15843 		 * tcp_deferred_acks_max is default to 2.
15844 		 */
15845 		tcp->tcp_rack_abs_max =
15846 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
15847 	}
15848 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15849 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15850 	else
15851 		tcp->tcp_rack_cur_max = 0;
15852 	/*
15853 	 * Increment the current rwnd by the amount the maximum grew (we
15854 	 * can not overwrite it since we might be in the middle of a
15855 	 * connection.)
15856 	 */
15857 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15858 	tcp->tcp_recv_hiwater = rwnd;
15859 
15860 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15861 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15862 		tcp->tcp_cwnd_max = rwnd;
15863 
15864 	if (tcp_detached)
15865 		return (rwnd);
15866 
15867 	tcp_set_recv_threshold(tcp, rwnd >> 3);
15868 
15869 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp, rwnd);
15870 	return (rwnd);
15871 }
15872 
15873 /*
15874  * Return SNMP stuff in buffer in mpdata.
15875  */
15876 mblk_t *
15877 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15878 {
15879 	mblk_t			*mpdata;
15880 	mblk_t			*mp_conn_ctl = NULL;
15881 	mblk_t			*mp_conn_tail;
15882 	mblk_t			*mp_attr_ctl = NULL;
15883 	mblk_t			*mp_attr_tail;
15884 	mblk_t			*mp6_conn_ctl = NULL;
15885 	mblk_t			*mp6_conn_tail;
15886 	mblk_t			*mp6_attr_ctl = NULL;
15887 	mblk_t			*mp6_attr_tail;
15888 	struct opthdr		*optp;
15889 	mib2_tcpConnEntry_t	tce;
15890 	mib2_tcp6ConnEntry_t	tce6;
15891 	mib2_transportMLPEntry_t mlp;
15892 	connf_t			*connfp;
15893 	int			i;
15894 	boolean_t 		ispriv;
15895 	zoneid_t 		zoneid;
15896 	int			v4_conn_idx;
15897 	int			v6_conn_idx;
15898 	conn_t			*connp = Q_TO_CONN(q);
15899 	tcp_stack_t		*tcps;
15900 	ip_stack_t		*ipst;
15901 	mblk_t			*mp2ctl;
15902 
15903 	/*
15904 	 * make a copy of the original message
15905 	 */
15906 	mp2ctl = copymsg(mpctl);
15907 
15908 	if (mpctl == NULL ||
15909 	    (mpdata = mpctl->b_cont) == NULL ||
15910 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15911 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
15912 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
15913 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
15914 		freemsg(mp_conn_ctl);
15915 		freemsg(mp_attr_ctl);
15916 		freemsg(mp6_conn_ctl);
15917 		freemsg(mp6_attr_ctl);
15918 		freemsg(mpctl);
15919 		freemsg(mp2ctl);
15920 		return (NULL);
15921 	}
15922 
15923 	ipst = connp->conn_netstack->netstack_ip;
15924 	tcps = connp->conn_netstack->netstack_tcp;
15925 
15926 	/* build table of connections -- need count in fixed part */
15927 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
15928 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
15929 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
15930 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
15931 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
15932 
15933 	ispriv =
15934 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15935 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15936 
15937 	v4_conn_idx = v6_conn_idx = 0;
15938 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
15939 
15940 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15941 		ipst = tcps->tcps_netstack->netstack_ip;
15942 
15943 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
15944 
15945 		connp = NULL;
15946 
15947 		while ((connp =
15948 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15949 			tcp_t *tcp;
15950 			boolean_t needattr;
15951 
15952 			if (connp->conn_zoneid != zoneid)
15953 				continue;	/* not in this zone */
15954 
15955 			tcp = connp->conn_tcp;
15956 			UPDATE_MIB(&tcps->tcps_mib,
15957 			    tcpHCInSegs, tcp->tcp_ibsegs);
15958 			tcp->tcp_ibsegs = 0;
15959 			UPDATE_MIB(&tcps->tcps_mib,
15960 			    tcpHCOutSegs, tcp->tcp_obsegs);
15961 			tcp->tcp_obsegs = 0;
15962 
15963 			tce6.tcp6ConnState = tce.tcpConnState =
15964 			    tcp_snmp_state(tcp);
15965 			if (tce.tcpConnState == MIB2_TCP_established ||
15966 			    tce.tcpConnState == MIB2_TCP_closeWait)
15967 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
15968 
15969 			needattr = B_FALSE;
15970 			bzero(&mlp, sizeof (mlp));
15971 			if (connp->conn_mlp_type != mlptSingle) {
15972 				if (connp->conn_mlp_type == mlptShared ||
15973 				    connp->conn_mlp_type == mlptBoth)
15974 					mlp.tme_flags |= MIB2_TMEF_SHARED;
15975 				if (connp->conn_mlp_type == mlptPrivate ||
15976 				    connp->conn_mlp_type == mlptBoth)
15977 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
15978 				needattr = B_TRUE;
15979 			}
15980 			if (connp->conn_anon_mlp) {
15981 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
15982 				needattr = B_TRUE;
15983 			}
15984 			if (connp->conn_mac_exempt) {
15985 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
15986 				needattr = B_TRUE;
15987 			}
15988 			if (connp->conn_fully_bound &&
15989 			    connp->conn_effective_cred != NULL) {
15990 				ts_label_t *tsl;
15991 
15992 				tsl = crgetlabel(connp->conn_effective_cred);
15993 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
15994 				mlp.tme_doi = label2doi(tsl);
15995 				mlp.tme_label = *label2bslabel(tsl);
15996 				needattr = B_TRUE;
15997 			}
15998 
15999 			/* Create a message to report on IPv6 entries */
16000 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16001 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16002 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16003 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16004 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16005 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16006 			/* Don't want just anybody seeing these... */
16007 			if (ispriv) {
16008 				tce6.tcp6ConnEntryInfo.ce_snxt =
16009 				    tcp->tcp_snxt;
16010 				tce6.tcp6ConnEntryInfo.ce_suna =
16011 				    tcp->tcp_suna;
16012 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16013 				    tcp->tcp_rnxt;
16014 				tce6.tcp6ConnEntryInfo.ce_rack =
16015 				    tcp->tcp_rack;
16016 			} else {
16017 				/*
16018 				 * Netstat, unfortunately, uses this to
16019 				 * get send/receive queue sizes.  How to fix?
16020 				 * Why not compute the difference only?
16021 				 */
16022 				tce6.tcp6ConnEntryInfo.ce_snxt =
16023 				    tcp->tcp_snxt - tcp->tcp_suna;
16024 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16025 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16026 				    tcp->tcp_rnxt - tcp->tcp_rack;
16027 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16028 			}
16029 
16030 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16031 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16032 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16033 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16034 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16035 
16036 			tce6.tcp6ConnCreationProcess =
16037 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16038 			    tcp->tcp_cpid;
16039 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16040 
16041 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16042 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16043 
16044 			mlp.tme_connidx = v6_conn_idx++;
16045 			if (needattr)
16046 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16047 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16048 			}
16049 			/*
16050 			 * Create an IPv4 table entry for IPv4 entries and also
16051 			 * for IPv6 entries which are bound to in6addr_any
16052 			 * but don't have IPV6_V6ONLY set.
16053 			 * (i.e. anything an IPv4 peer could connect to)
16054 			 */
16055 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16056 			    (tcp->tcp_state <= TCPS_LISTEN &&
16057 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16058 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16059 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16060 					tce.tcpConnRemAddress = INADDR_ANY;
16061 					tce.tcpConnLocalAddress = INADDR_ANY;
16062 				} else {
16063 					tce.tcpConnRemAddress =
16064 					    tcp->tcp_remote;
16065 					tce.tcpConnLocalAddress =
16066 					    tcp->tcp_ip_src;
16067 				}
16068 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16069 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16070 				/* Don't want just anybody seeing these... */
16071 				if (ispriv) {
16072 					tce.tcpConnEntryInfo.ce_snxt =
16073 					    tcp->tcp_snxt;
16074 					tce.tcpConnEntryInfo.ce_suna =
16075 					    tcp->tcp_suna;
16076 					tce.tcpConnEntryInfo.ce_rnxt =
16077 					    tcp->tcp_rnxt;
16078 					tce.tcpConnEntryInfo.ce_rack =
16079 					    tcp->tcp_rack;
16080 				} else {
16081 					/*
16082 					 * Netstat, unfortunately, uses this to
16083 					 * get send/receive queue sizes.  How
16084 					 * to fix?
16085 					 * Why not compute the difference only?
16086 					 */
16087 					tce.tcpConnEntryInfo.ce_snxt =
16088 					    tcp->tcp_snxt - tcp->tcp_suna;
16089 					tce.tcpConnEntryInfo.ce_suna = 0;
16090 					tce.tcpConnEntryInfo.ce_rnxt =
16091 					    tcp->tcp_rnxt - tcp->tcp_rack;
16092 					tce.tcpConnEntryInfo.ce_rack = 0;
16093 				}
16094 
16095 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16096 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16097 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16098 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16099 				tce.tcpConnEntryInfo.ce_state =
16100 				    tcp->tcp_state;
16101 
16102 				tce.tcpConnCreationProcess =
16103 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16104 				    tcp->tcp_cpid;
16105 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16106 
16107 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16108 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16109 
16110 				mlp.tme_connidx = v4_conn_idx++;
16111 				if (needattr)
16112 					(void) snmp_append_data2(
16113 					    mp_attr_ctl->b_cont,
16114 					    &mp_attr_tail, (char *)&mlp,
16115 					    sizeof (mlp));
16116 			}
16117 		}
16118 	}
16119 
16120 	/* fixed length structure for IPv4 and IPv6 counters */
16121 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16122 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16123 	    sizeof (mib2_tcp6ConnEntry_t));
16124 	/* synchronize 32- and 64-bit counters */
16125 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16126 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16127 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16128 	optp->level = MIB2_TCP;
16129 	optp->name = 0;
16130 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16131 	    sizeof (tcps->tcps_mib));
16132 	optp->len = msgdsize(mpdata);
16133 	qreply(q, mpctl);
16134 
16135 	/* table of connections... */
16136 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16137 	    sizeof (struct T_optmgmt_ack)];
16138 	optp->level = MIB2_TCP;
16139 	optp->name = MIB2_TCP_CONN;
16140 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16141 	qreply(q, mp_conn_ctl);
16142 
16143 	/* table of MLP attributes... */
16144 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16145 	    sizeof (struct T_optmgmt_ack)];
16146 	optp->level = MIB2_TCP;
16147 	optp->name = EXPER_XPORT_MLP;
16148 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16149 	if (optp->len == 0)
16150 		freemsg(mp_attr_ctl);
16151 	else
16152 		qreply(q, mp_attr_ctl);
16153 
16154 	/* table of IPv6 connections... */
16155 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16156 	    sizeof (struct T_optmgmt_ack)];
16157 	optp->level = MIB2_TCP6;
16158 	optp->name = MIB2_TCP6_CONN;
16159 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16160 	qreply(q, mp6_conn_ctl);
16161 
16162 	/* table of IPv6 MLP attributes... */
16163 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16164 	    sizeof (struct T_optmgmt_ack)];
16165 	optp->level = MIB2_TCP6;
16166 	optp->name = EXPER_XPORT_MLP;
16167 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16168 	if (optp->len == 0)
16169 		freemsg(mp6_attr_ctl);
16170 	else
16171 		qreply(q, mp6_attr_ctl);
16172 	return (mp2ctl);
16173 }
16174 
16175 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16176 /* ARGSUSED */
16177 int
16178 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16179 {
16180 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16181 
16182 	switch (level) {
16183 	case MIB2_TCP:
16184 		switch (name) {
16185 		case 13:
16186 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16187 				return (0);
16188 			/* TODO: delete entry defined by tce */
16189 			return (1);
16190 		default:
16191 			return (0);
16192 		}
16193 	default:
16194 		return (1);
16195 	}
16196 }
16197 
16198 /* Translate TCP state to MIB2 TCP state. */
16199 static int
16200 tcp_snmp_state(tcp_t *tcp)
16201 {
16202 	if (tcp == NULL)
16203 		return (0);
16204 
16205 	switch (tcp->tcp_state) {
16206 	case TCPS_CLOSED:
16207 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16208 	case TCPS_BOUND:
16209 		return (MIB2_TCP_closed);
16210 	case TCPS_LISTEN:
16211 		return (MIB2_TCP_listen);
16212 	case TCPS_SYN_SENT:
16213 		return (MIB2_TCP_synSent);
16214 	case TCPS_SYN_RCVD:
16215 		return (MIB2_TCP_synReceived);
16216 	case TCPS_ESTABLISHED:
16217 		return (MIB2_TCP_established);
16218 	case TCPS_CLOSE_WAIT:
16219 		return (MIB2_TCP_closeWait);
16220 	case TCPS_FIN_WAIT_1:
16221 		return (MIB2_TCP_finWait1);
16222 	case TCPS_CLOSING:
16223 		return (MIB2_TCP_closing);
16224 	case TCPS_LAST_ACK:
16225 		return (MIB2_TCP_lastAck);
16226 	case TCPS_FIN_WAIT_2:
16227 		return (MIB2_TCP_finWait2);
16228 	case TCPS_TIME_WAIT:
16229 		return (MIB2_TCP_timeWait);
16230 	default:
16231 		return (0);
16232 	}
16233 }
16234 
16235 /*
16236  * tcp_timer is the timer service routine.  It handles the retransmission,
16237  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16238  * from the state of the tcp instance what kind of action needs to be done
16239  * at the time it is called.
16240  */
16241 static void
16242 tcp_timer(void *arg)
16243 {
16244 	mblk_t		*mp;
16245 	clock_t		first_threshold;
16246 	clock_t		second_threshold;
16247 	clock_t		ms;
16248 	uint32_t	mss;
16249 	conn_t		*connp = (conn_t *)arg;
16250 	tcp_t		*tcp = connp->conn_tcp;
16251 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16252 
16253 	tcp->tcp_timer_tid = 0;
16254 
16255 	if (tcp->tcp_fused)
16256 		return;
16257 
16258 	first_threshold =  tcp->tcp_first_timer_threshold;
16259 	second_threshold = tcp->tcp_second_timer_threshold;
16260 	switch (tcp->tcp_state) {
16261 	case TCPS_IDLE:
16262 	case TCPS_BOUND:
16263 	case TCPS_LISTEN:
16264 		return;
16265 	case TCPS_SYN_RCVD: {
16266 		tcp_t	*listener = tcp->tcp_listener;
16267 
16268 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16269 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16270 			/* it's our first timeout */
16271 			tcp->tcp_syn_rcvd_timeout = 1;
16272 			mutex_enter(&listener->tcp_eager_lock);
16273 			listener->tcp_syn_rcvd_timeout++;
16274 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16275 				/*
16276 				 * Make this eager available for drop if we
16277 				 * need to drop one to accomodate a new
16278 				 * incoming SYN request.
16279 				 */
16280 				MAKE_DROPPABLE(listener, tcp);
16281 			}
16282 			if (!listener->tcp_syn_defense &&
16283 			    (listener->tcp_syn_rcvd_timeout >
16284 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16285 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16286 				/* We may be under attack. Put on a defense. */
16287 				listener->tcp_syn_defense = B_TRUE;
16288 				cmn_err(CE_WARN, "High TCP connect timeout "
16289 				    "rate! System (port %d) may be under a "
16290 				    "SYN flood attack!",
16291 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16292 
16293 				listener->tcp_ip_addr_cache = kmem_zalloc(
16294 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16295 				    KM_NOSLEEP);
16296 			}
16297 			mutex_exit(&listener->tcp_eager_lock);
16298 		} else if (listener != NULL) {
16299 			mutex_enter(&listener->tcp_eager_lock);
16300 			tcp->tcp_syn_rcvd_timeout++;
16301 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16302 			    !tcp->tcp_closemp_used) {
16303 				/*
16304 				 * This is our second timeout. Put the tcp in
16305 				 * the list of droppable eagers to allow it to
16306 				 * be dropped, if needed. We don't check
16307 				 * whether tcp_dontdrop is set or not to
16308 				 * protect ourselve from a SYN attack where a
16309 				 * remote host can spoof itself as one of the
16310 				 * good IP source and continue to hold
16311 				 * resources too long.
16312 				 */
16313 				MAKE_DROPPABLE(listener, tcp);
16314 			}
16315 			mutex_exit(&listener->tcp_eager_lock);
16316 		}
16317 	}
16318 		/* FALLTHRU */
16319 	case TCPS_SYN_SENT:
16320 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16321 		second_threshold = tcp->tcp_second_ctimer_threshold;
16322 		break;
16323 	case TCPS_ESTABLISHED:
16324 	case TCPS_FIN_WAIT_1:
16325 	case TCPS_CLOSING:
16326 	case TCPS_CLOSE_WAIT:
16327 	case TCPS_LAST_ACK:
16328 		/* If we have data to rexmit */
16329 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16330 			clock_t	time_to_wait;
16331 
16332 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
16333 			if (!tcp->tcp_xmit_head)
16334 				break;
16335 			time_to_wait = lbolt -
16336 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16337 			time_to_wait = tcp->tcp_rto -
16338 			    TICK_TO_MSEC(time_to_wait);
16339 			/*
16340 			 * If the timer fires too early, 1 clock tick earlier,
16341 			 * restart the timer.
16342 			 */
16343 			if (time_to_wait > msec_per_tick) {
16344 				TCP_STAT(tcps, tcp_timer_fire_early);
16345 				TCP_TIMER_RESTART(tcp, time_to_wait);
16346 				return;
16347 			}
16348 			/*
16349 			 * When we probe zero windows, we force the swnd open.
16350 			 * If our peer acks with a closed window swnd will be
16351 			 * set to zero by tcp_rput(). As long as we are
16352 			 * receiving acks tcp_rput will
16353 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16354 			 * first and second interval actions.  NOTE: the timer
16355 			 * interval is allowed to continue its exponential
16356 			 * backoff.
16357 			 */
16358 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16359 				if (tcp->tcp_debug) {
16360 					(void) strlog(TCP_MOD_ID, 0, 1,
16361 					    SL_TRACE, "tcp_timer: zero win");
16362 				}
16363 			} else {
16364 				/*
16365 				 * After retransmission, we need to do
16366 				 * slow start.  Set the ssthresh to one
16367 				 * half of current effective window and
16368 				 * cwnd to one MSS.  Also reset
16369 				 * tcp_cwnd_cnt.
16370 				 *
16371 				 * Note that if tcp_ssthresh is reduced because
16372 				 * of ECN, do not reduce it again unless it is
16373 				 * already one window of data away (tcp_cwr
16374 				 * should then be cleared) or this is a
16375 				 * timeout for a retransmitted segment.
16376 				 */
16377 				uint32_t npkt;
16378 
16379 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16380 					npkt = ((tcp->tcp_timer_backoff ?
16381 					    tcp->tcp_cwnd_ssthresh :
16382 					    tcp->tcp_snxt -
16383 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16384 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16385 					    tcp->tcp_mss;
16386 				}
16387 				tcp->tcp_cwnd = tcp->tcp_mss;
16388 				tcp->tcp_cwnd_cnt = 0;
16389 				if (tcp->tcp_ecn_ok) {
16390 					tcp->tcp_cwr = B_TRUE;
16391 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16392 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16393 				}
16394 			}
16395 			break;
16396 		}
16397 		/*
16398 		 * We have something to send yet we cannot send.  The
16399 		 * reason can be:
16400 		 *
16401 		 * 1. Zero send window: we need to do zero window probe.
16402 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16403 		 * segments.
16404 		 * 3. SWS avoidance: receiver may have shrunk window,
16405 		 * reset our knowledge.
16406 		 *
16407 		 * Note that condition 2 can happen with either 1 or
16408 		 * 3.  But 1 and 3 are exclusive.
16409 		 */
16410 		if (tcp->tcp_unsent != 0) {
16411 			if (tcp->tcp_cwnd == 0) {
16412 				/*
16413 				 * Set tcp_cwnd to 1 MSS so that a
16414 				 * new segment can be sent out.  We
16415 				 * are "clocking out" new data when
16416 				 * the network is really congested.
16417 				 */
16418 				ASSERT(tcp->tcp_ecn_ok);
16419 				tcp->tcp_cwnd = tcp->tcp_mss;
16420 			}
16421 			if (tcp->tcp_swnd == 0) {
16422 				/* Extend window for zero window probe */
16423 				tcp->tcp_swnd++;
16424 				tcp->tcp_zero_win_probe = B_TRUE;
16425 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
16426 			} else {
16427 				/*
16428 				 * Handle timeout from sender SWS avoidance.
16429 				 * Reset our knowledge of the max send window
16430 				 * since the receiver might have reduced its
16431 				 * receive buffer.  Avoid setting tcp_max_swnd
16432 				 * to one since that will essentially disable
16433 				 * the SWS checks.
16434 				 *
16435 				 * Note that since we don't have a SWS
16436 				 * state variable, if the timeout is set
16437 				 * for ECN but not for SWS, this
16438 				 * code will also be executed.  This is
16439 				 * fine as tcp_max_swnd is updated
16440 				 * constantly and it will not affect
16441 				 * anything.
16442 				 */
16443 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16444 			}
16445 			tcp_wput_data(tcp, NULL, B_FALSE);
16446 			return;
16447 		}
16448 		/* Is there a FIN that needs to be to re retransmitted? */
16449 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16450 		    !tcp->tcp_fin_acked)
16451 			break;
16452 		/* Nothing to do, return without restarting timer. */
16453 		TCP_STAT(tcps, tcp_timer_fire_miss);
16454 		return;
16455 	case TCPS_FIN_WAIT_2:
16456 		/*
16457 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16458 		 * We waited some time for for peer's FIN, but it hasn't
16459 		 * arrived.  We flush the connection now to avoid
16460 		 * case where the peer has rebooted.
16461 		 */
16462 		if (TCP_IS_DETACHED(tcp)) {
16463 			(void) tcp_clean_death(tcp, 0, 23);
16464 		} else {
16465 			TCP_TIMER_RESTART(tcp,
16466 			    tcps->tcps_fin_wait_2_flush_interval);
16467 		}
16468 		return;
16469 	case TCPS_TIME_WAIT:
16470 		(void) tcp_clean_death(tcp, 0, 24);
16471 		return;
16472 	default:
16473 		if (tcp->tcp_debug) {
16474 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16475 			    "tcp_timer: strange state (%d) %s",
16476 			    tcp->tcp_state, tcp_display(tcp, NULL,
16477 			    DISP_PORT_ONLY));
16478 		}
16479 		return;
16480 	}
16481 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16482 		/*
16483 		 * For zero window probe, we need to send indefinitely,
16484 		 * unless we have not heard from the other side for some
16485 		 * time...
16486 		 */
16487 		if ((tcp->tcp_zero_win_probe == 0) ||
16488 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16489 		    second_threshold)) {
16490 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
16491 			/*
16492 			 * If TCP is in SYN_RCVD state, send back a
16493 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16494 			 * should be zero in TCPS_SYN_RCVD state.
16495 			 */
16496 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16497 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16498 				    "in SYN_RCVD",
16499 				    tcp, tcp->tcp_snxt,
16500 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16501 			}
16502 			(void) tcp_clean_death(tcp,
16503 			    tcp->tcp_client_errno ?
16504 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16505 			return;
16506 		} else {
16507 			/*
16508 			 * Set tcp_ms_we_have_waited to second_threshold
16509 			 * so that in next timeout, we will do the above
16510 			 * check (lbolt - tcp_last_recv_time).  This is
16511 			 * also to avoid overflow.
16512 			 *
16513 			 * We don't need to decrement tcp_timer_backoff
16514 			 * to avoid overflow because it will be decremented
16515 			 * later if new timeout value is greater than
16516 			 * tcp_rexmit_interval_max.  In the case when
16517 			 * tcp_rexmit_interval_max is greater than
16518 			 * second_threshold, it means that we will wait
16519 			 * longer than second_threshold to send the next
16520 			 * window probe.
16521 			 */
16522 			tcp->tcp_ms_we_have_waited = second_threshold;
16523 		}
16524 	} else if (ms > first_threshold) {
16525 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16526 		    tcp->tcp_xmit_head != NULL) {
16527 			tcp->tcp_xmit_head =
16528 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16529 		}
16530 		/*
16531 		 * We have been retransmitting for too long...  The RTT
16532 		 * we calculated is probably incorrect.  Reinitialize it.
16533 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16534 		 * tcp_rtt_update so that we won't accidentally cache a
16535 		 * bad value.  But only do this if this is not a zero
16536 		 * window probe.
16537 		 */
16538 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16539 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16540 			    (tcp->tcp_rtt_sa >> 5);
16541 			tcp->tcp_rtt_sa = 0;
16542 			tcp_ip_notify(tcp);
16543 			tcp->tcp_rtt_update = 0;
16544 		}
16545 	}
16546 	tcp->tcp_timer_backoff++;
16547 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16548 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16549 	    tcps->tcps_rexmit_interval_min) {
16550 		/*
16551 		 * This means the original RTO is tcp_rexmit_interval_min.
16552 		 * So we will use tcp_rexmit_interval_min as the RTO value
16553 		 * and do the backoff.
16554 		 */
16555 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
16556 	} else {
16557 		ms <<= tcp->tcp_timer_backoff;
16558 	}
16559 	if (ms > tcps->tcps_rexmit_interval_max) {
16560 		ms = tcps->tcps_rexmit_interval_max;
16561 		/*
16562 		 * ms is at max, decrement tcp_timer_backoff to avoid
16563 		 * overflow.
16564 		 */
16565 		tcp->tcp_timer_backoff--;
16566 	}
16567 	tcp->tcp_ms_we_have_waited += ms;
16568 	if (tcp->tcp_zero_win_probe == 0) {
16569 		tcp->tcp_rto = ms;
16570 	}
16571 	TCP_TIMER_RESTART(tcp, ms);
16572 	/*
16573 	 * This is after a timeout and tcp_rto is backed off.  Set
16574 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16575 	 * restart the timer with a correct value.
16576 	 */
16577 	tcp->tcp_set_timer = 1;
16578 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16579 	if (mss > tcp->tcp_mss)
16580 		mss = tcp->tcp_mss;
16581 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16582 		mss = tcp->tcp_swnd;
16583 
16584 	if ((mp = tcp->tcp_xmit_head) != NULL)
16585 		mp->b_prev = (mblk_t *)lbolt;
16586 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16587 	    B_TRUE);
16588 
16589 	/*
16590 	 * When slow start after retransmission begins, start with
16591 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16592 	 * start phase.  tcp_snd_burst controls how many segments
16593 	 * can be sent because of an ack.
16594 	 */
16595 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16596 	tcp->tcp_snd_burst = TCP_CWND_SS;
16597 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16598 	    (tcp->tcp_unsent == 0)) {
16599 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16600 	} else {
16601 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16602 	}
16603 	tcp->tcp_rexmit = B_TRUE;
16604 	tcp->tcp_dupack_cnt = 0;
16605 
16606 	/*
16607 	 * Remove all rexmit SACK blk to start from fresh.
16608 	 */
16609 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
16610 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
16611 	if (mp == NULL) {
16612 		return;
16613 	}
16614 	/*
16615 	 * Attach credentials to retransmitted initial SYNs.
16616 	 * In theory we should use the credentials from the connect()
16617 	 * call to ensure that getpeerucred() on the peer will be correct.
16618 	 * But we assume that SYN's are not dropped for loopback connections.
16619 	 */
16620 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16621 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp), tcp->tcp_cpid);
16622 	}
16623 
16624 	tcp->tcp_csuna = tcp->tcp_snxt;
16625 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
16626 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
16627 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16628 
16629 }
16630 
16631 static int
16632 tcp_do_unbind(conn_t *connp)
16633 {
16634 	tcp_t *tcp = connp->conn_tcp;
16635 	int error = 0;
16636 
16637 	switch (tcp->tcp_state) {
16638 	case TCPS_BOUND:
16639 	case TCPS_LISTEN:
16640 		break;
16641 	default:
16642 		return (-TOUTSTATE);
16643 	}
16644 
16645 	/*
16646 	 * Need to clean up all the eagers since after the unbind, segments
16647 	 * will no longer be delivered to this listener stream.
16648 	 */
16649 	mutex_enter(&tcp->tcp_eager_lock);
16650 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16651 		tcp_eager_cleanup(tcp, 0);
16652 	}
16653 	mutex_exit(&tcp->tcp_eager_lock);
16654 
16655 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16656 		tcp->tcp_ipha->ipha_src = 0;
16657 	} else {
16658 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16659 	}
16660 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16661 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16662 	tcp_bind_hash_remove(tcp);
16663 	tcp->tcp_state = TCPS_IDLE;
16664 	tcp->tcp_mdt = B_FALSE;
16665 
16666 	connp = tcp->tcp_connp;
16667 	connp->conn_mdt_ok = B_FALSE;
16668 	ipcl_hash_remove(connp);
16669 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16670 
16671 	return (error);
16672 }
16673 
16674 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16675 static void
16676 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
16677 {
16678 	int error = tcp_do_unbind(tcp->tcp_connp);
16679 
16680 	if (error > 0) {
16681 		tcp_err_ack(tcp, mp, TSYSERR, error);
16682 	} else if (error < 0) {
16683 		tcp_err_ack(tcp, mp, -error, 0);
16684 	} else {
16685 		/* Send M_FLUSH according to TPI */
16686 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16687 
16688 		mp = mi_tpi_ok_ack_alloc(mp);
16689 		putnext(tcp->tcp_rq, mp);
16690 	}
16691 }
16692 
16693 /*
16694  * Don't let port fall into the privileged range.
16695  * Since the extra privileged ports can be arbitrary we also
16696  * ensure that we exclude those from consideration.
16697  * tcp_g_epriv_ports is not sorted thus we loop over it until
16698  * there are no changes.
16699  *
16700  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16701  * but instead the code relies on:
16702  * - the fact that the address of the array and its size never changes
16703  * - the atomic assignment of the elements of the array
16704  *
16705  * Returns 0 if there are no more ports available.
16706  *
16707  * TS note: skip multilevel ports.
16708  */
16709 static in_port_t
16710 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16711 {
16712 	int i;
16713 	boolean_t restart = B_FALSE;
16714 	tcp_stack_t *tcps = tcp->tcp_tcps;
16715 
16716 	if (random && tcp_random_anon_port != 0) {
16717 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16718 		    sizeof (in_port_t));
16719 		/*
16720 		 * Unless changed by a sys admin, the smallest anon port
16721 		 * is 32768 and the largest anon port is 65535.  It is
16722 		 * very likely (50%) for the random port to be smaller
16723 		 * than the smallest anon port.  When that happens,
16724 		 * add port % (anon port range) to the smallest anon
16725 		 * port to get the random port.  It should fall into the
16726 		 * valid anon port range.
16727 		 */
16728 		if (port < tcps->tcps_smallest_anon_port) {
16729 			port = tcps->tcps_smallest_anon_port +
16730 			    port % (tcps->tcps_largest_anon_port -
16731 			    tcps->tcps_smallest_anon_port);
16732 		}
16733 	}
16734 
16735 retry:
16736 	if (port < tcps->tcps_smallest_anon_port)
16737 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16738 
16739 	if (port > tcps->tcps_largest_anon_port) {
16740 		if (restart)
16741 			return (0);
16742 		restart = B_TRUE;
16743 		port = (in_port_t)tcps->tcps_smallest_anon_port;
16744 	}
16745 
16746 	if (port < tcps->tcps_smallest_nonpriv_port)
16747 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
16748 
16749 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
16750 		if (port == tcps->tcps_g_epriv_ports[i]) {
16751 			port++;
16752 			/*
16753 			 * Make sure whether the port is in the
16754 			 * valid range.
16755 			 */
16756 			goto retry;
16757 		}
16758 	}
16759 	if (is_system_labeled() &&
16760 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
16761 	    IPPROTO_TCP, B_TRUE)) != 0) {
16762 		port = i;
16763 		goto retry;
16764 	}
16765 	return (port);
16766 }
16767 
16768 /*
16769  * Return the next anonymous port in the privileged port range for
16770  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16771  * downwards.  This is the same behavior as documented in the userland
16772  * library call rresvport(3N).
16773  *
16774  * TS note: skip multilevel ports.
16775  */
16776 static in_port_t
16777 tcp_get_next_priv_port(const tcp_t *tcp)
16778 {
16779 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16780 	in_port_t nextport;
16781 	boolean_t restart = B_FALSE;
16782 	tcp_stack_t *tcps = tcp->tcp_tcps;
16783 retry:
16784 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
16785 	    next_priv_port >= IPPORT_RESERVED) {
16786 		next_priv_port = IPPORT_RESERVED - 1;
16787 		if (restart)
16788 			return (0);
16789 		restart = B_TRUE;
16790 	}
16791 	if (is_system_labeled() &&
16792 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
16793 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
16794 		next_priv_port = nextport;
16795 		goto retry;
16796 	}
16797 	return (next_priv_port--);
16798 }
16799 
16800 /* The write side r/w procedure. */
16801 
16802 #if CCS_STATS
16803 struct {
16804 	struct {
16805 		int64_t count, bytes;
16806 	} tot, hit;
16807 } wrw_stats;
16808 #endif
16809 
16810 /*
16811  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16812  * messages.
16813  */
16814 /* ARGSUSED */
16815 static void
16816 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16817 {
16818 	conn_t	*connp = (conn_t *)arg;
16819 	tcp_t	*tcp = connp->conn_tcp;
16820 	queue_t	*q = tcp->tcp_wq;
16821 
16822 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16823 	/*
16824 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16825 	 * Once the close starts, streamhead and sockfs will not let any data
16826 	 * packets come down (close ensures that there are no threads using the
16827 	 * queue and no new threads will come down) but since qprocsoff()
16828 	 * hasn't happened yet, a M_FLUSH or some non data message might
16829 	 * get reflected back (in response to our own FLUSHRW) and get
16830 	 * processed after tcp_close() is done. The conn would still be valid
16831 	 * because a ref would have added but we need to check the state
16832 	 * before actually processing the packet.
16833 	 */
16834 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16835 		freemsg(mp);
16836 		return;
16837 	}
16838 
16839 	switch (DB_TYPE(mp)) {
16840 	case M_IOCDATA:
16841 		tcp_wput_iocdata(tcp, mp);
16842 		break;
16843 	case M_FLUSH:
16844 		tcp_wput_flush(tcp, mp);
16845 		break;
16846 	default:
16847 		CALL_IP_WPUT(connp, q, mp);
16848 		break;
16849 	}
16850 }
16851 
16852 /*
16853  * The TCP fast path write put procedure.
16854  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16855  */
16856 /* ARGSUSED */
16857 void
16858 tcp_output(void *arg, mblk_t *mp, void *arg2)
16859 {
16860 	int		len;
16861 	int		hdrlen;
16862 	int		plen;
16863 	mblk_t		*mp1;
16864 	uchar_t		*rptr;
16865 	uint32_t	snxt;
16866 	tcph_t		*tcph;
16867 	struct datab	*db;
16868 	uint32_t	suna;
16869 	uint32_t	mss;
16870 	ipaddr_t	*dst;
16871 	ipaddr_t	*src;
16872 	uint32_t	sum;
16873 	int		usable;
16874 	conn_t		*connp = (conn_t *)arg;
16875 	tcp_t		*tcp = connp->conn_tcp;
16876 	uint32_t	msize;
16877 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16878 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
16879 
16880 	/*
16881 	 * Try and ASSERT the minimum possible references on the
16882 	 * conn early enough. Since we are executing on write side,
16883 	 * the connection is obviously not detached and that means
16884 	 * there is a ref each for TCP and IP. Since we are behind
16885 	 * the squeue, the minimum references needed are 3. If the
16886 	 * conn is in classifier hash list, there should be an
16887 	 * extra ref for that (we check both the possibilities).
16888 	 */
16889 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16890 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16891 
16892 	ASSERT(DB_TYPE(mp) == M_DATA);
16893 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
16894 
16895 	mutex_enter(&tcp->tcp_non_sq_lock);
16896 	tcp->tcp_squeue_bytes -= msize;
16897 	mutex_exit(&tcp->tcp_non_sq_lock);
16898 
16899 	/* Check to see if this connection wants to be re-fused. */
16900 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
16901 		if (tcp->tcp_ipversion == IPV4_VERSION) {
16902 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
16903 			    &tcp->tcp_saved_tcph);
16904 		} else {
16905 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
16906 			    &tcp->tcp_saved_tcph);
16907 		}
16908 	}
16909 	/* Bypass tcp protocol for fused tcp loopback */
16910 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
16911 		return;
16912 
16913 	mss = tcp->tcp_mss;
16914 	if (tcp->tcp_xmit_zc_clean)
16915 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16916 
16917 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16918 	len = (int)(mp->b_wptr - mp->b_rptr);
16919 
16920 	/*
16921 	 * Criteria for fast path:
16922 	 *
16923 	 *   1. no unsent data
16924 	 *   2. single mblk in request
16925 	 *   3. connection established
16926 	 *   4. data in mblk
16927 	 *   5. len <= mss
16928 	 *   6. no tcp_valid bits
16929 	 */
16930 	if ((tcp->tcp_unsent != 0) ||
16931 	    (tcp->tcp_cork) ||
16932 	    (mp->b_cont != NULL) ||
16933 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16934 	    (len == 0) ||
16935 	    (len > mss) ||
16936 	    (tcp->tcp_valid_bits != 0)) {
16937 		tcp_wput_data(tcp, mp, B_FALSE);
16938 		return;
16939 	}
16940 
16941 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16942 	ASSERT(tcp->tcp_fin_sent == 0);
16943 
16944 	/* queue new packet onto retransmission queue */
16945 	if (tcp->tcp_xmit_head == NULL) {
16946 		tcp->tcp_xmit_head = mp;
16947 	} else {
16948 		tcp->tcp_xmit_last->b_cont = mp;
16949 	}
16950 	tcp->tcp_xmit_last = mp;
16951 	tcp->tcp_xmit_tail = mp;
16952 
16953 	/* find out how much we can send */
16954 	/* BEGIN CSTYLED */
16955 	/*
16956 	 *    un-acked	   usable
16957 	 *  |--------------|-----------------|
16958 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
16959 	 */
16960 	/* END CSTYLED */
16961 
16962 	/* start sending from tcp_snxt */
16963 	snxt = tcp->tcp_snxt;
16964 
16965 	/*
16966 	 * Check to see if this connection has been idled for some
16967 	 * time and no ACK is expected.  If it is, we need to slow
16968 	 * start again to get back the connection's "self-clock" as
16969 	 * described in VJ's paper.
16970 	 *
16971 	 * Refer to the comment in tcp_mss_set() for the calculation
16972 	 * of tcp_cwnd after idle.
16973 	 */
16974 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16975 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16976 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
16977 	}
16978 
16979 	usable = tcp->tcp_swnd;		/* tcp window size */
16980 	if (usable > tcp->tcp_cwnd)
16981 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16982 	usable -= snxt;		/* subtract stuff already sent */
16983 	suna = tcp->tcp_suna;
16984 	usable += suna;
16985 	/* usable can be < 0 if the congestion window is smaller */
16986 	if (len > usable) {
16987 		/* Can't send complete M_DATA in one shot */
16988 		goto slow;
16989 	}
16990 
16991 	mutex_enter(&tcp->tcp_non_sq_lock);
16992 	if (tcp->tcp_flow_stopped &&
16993 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16994 		tcp_clrqfull(tcp);
16995 	}
16996 	mutex_exit(&tcp->tcp_non_sq_lock);
16997 
16998 	/*
16999 	 * determine if anything to send (Nagle).
17000 	 *
17001 	 *   1. len < tcp_mss (i.e. small)
17002 	 *   2. unacknowledged data present
17003 	 *   3. len < nagle limit
17004 	 *   4. last packet sent < nagle limit (previous packet sent)
17005 	 */
17006 	if ((len < mss) && (snxt != suna) &&
17007 	    (len < (int)tcp->tcp_naglim) &&
17008 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17009 		/*
17010 		 * This was the first unsent packet and normally
17011 		 * mss < xmit_hiwater so there is no need to worry
17012 		 * about flow control. The next packet will go
17013 		 * through the flow control check in tcp_wput_data().
17014 		 */
17015 		/* leftover work from above */
17016 		tcp->tcp_unsent = len;
17017 		tcp->tcp_xmit_tail_unsent = len;
17018 
17019 		return;
17020 	}
17021 
17022 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17023 
17024 	if (snxt == suna) {
17025 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17026 	}
17027 
17028 	/* we have always sent something */
17029 	tcp->tcp_rack_cnt = 0;
17030 
17031 	tcp->tcp_snxt = snxt + len;
17032 	tcp->tcp_rack = tcp->tcp_rnxt;
17033 
17034 	if ((mp1 = dupb(mp)) == 0)
17035 		goto no_memory;
17036 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17037 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17038 
17039 	/* adjust tcp header information */
17040 	tcph = tcp->tcp_tcph;
17041 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17042 
17043 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17044 	sum = (sum >> 16) + (sum & 0xFFFF);
17045 	U16_TO_ABE16(sum, tcph->th_sum);
17046 
17047 	U32_TO_ABE32(snxt, tcph->th_seq);
17048 
17049 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17050 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17051 	BUMP_LOCAL(tcp->tcp_obsegs);
17052 
17053 	/* Update the latest receive window size in TCP header. */
17054 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17055 	    tcph->th_win);
17056 
17057 	tcp->tcp_last_sent_len = (ushort_t)len;
17058 
17059 	plen = len + tcp->tcp_hdr_len;
17060 
17061 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17062 		tcp->tcp_ipha->ipha_length = htons(plen);
17063 	} else {
17064 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17065 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17066 	}
17067 
17068 	/* see if we need to allocate a mblk for the headers */
17069 	hdrlen = tcp->tcp_hdr_len;
17070 	rptr = mp1->b_rptr - hdrlen;
17071 	db = mp1->b_datap;
17072 	if ((db->db_ref != 2) || rptr < db->db_base ||
17073 	    (!OK_32PTR(rptr))) {
17074 		/* NOTE: we assume allocb returns an OK_32PTR */
17075 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17076 		    tcps->tcps_wroff_xtra, BPRI_MED);
17077 		if (!mp) {
17078 			freemsg(mp1);
17079 			goto no_memory;
17080 		}
17081 		mp->b_cont = mp1;
17082 		mp1 = mp;
17083 		/* Leave room for Link Level header */
17084 		/* hdrlen = tcp->tcp_hdr_len; */
17085 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17086 		mp1->b_wptr = &rptr[hdrlen];
17087 	}
17088 	mp1->b_rptr = rptr;
17089 
17090 	/* Fill in the timestamp option. */
17091 	if (tcp->tcp_snd_ts_ok) {
17092 		U32_TO_BE32((uint32_t)lbolt,
17093 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17094 		U32_TO_BE32(tcp->tcp_ts_recent,
17095 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17096 	} else {
17097 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17098 	}
17099 
17100 	/* copy header into outgoing packet */
17101 	dst = (ipaddr_t *)rptr;
17102 	src = (ipaddr_t *)tcp->tcp_iphc;
17103 	dst[0] = src[0];
17104 	dst[1] = src[1];
17105 	dst[2] = src[2];
17106 	dst[3] = src[3];
17107 	dst[4] = src[4];
17108 	dst[5] = src[5];
17109 	dst[6] = src[6];
17110 	dst[7] = src[7];
17111 	dst[8] = src[8];
17112 	dst[9] = src[9];
17113 	if (hdrlen -= 40) {
17114 		hdrlen >>= 2;
17115 		dst += 10;
17116 		src += 10;
17117 		do {
17118 			*dst++ = *src++;
17119 		} while (--hdrlen);
17120 	}
17121 
17122 	/*
17123 	 * Set the ECN info in the TCP header.  Note that this
17124 	 * is not the template header.
17125 	 */
17126 	if (tcp->tcp_ecn_ok) {
17127 		SET_ECT(tcp, rptr);
17128 
17129 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17130 		if (tcp->tcp_ecn_echo_on)
17131 			tcph->th_flags[0] |= TH_ECE;
17132 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17133 			tcph->th_flags[0] |= TH_CWR;
17134 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17135 		}
17136 	}
17137 
17138 	if (tcp->tcp_ip_forward_progress) {
17139 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17140 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17141 		tcp->tcp_ip_forward_progress = B_FALSE;
17142 	}
17143 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17144 	return;
17145 
17146 	/*
17147 	 * If we ran out of memory, we pretend to have sent the packet
17148 	 * and that it was lost on the wire.
17149 	 */
17150 no_memory:
17151 	return;
17152 
17153 slow:
17154 	/* leftover work from above */
17155 	tcp->tcp_unsent = len;
17156 	tcp->tcp_xmit_tail_unsent = len;
17157 	tcp_wput_data(tcp, NULL, B_FALSE);
17158 }
17159 
17160 /* ARGSUSED */
17161 void
17162 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17163 {
17164 	conn_t			*connp = (conn_t *)arg;
17165 	tcp_t			*tcp = connp->conn_tcp;
17166 	queue_t			*q = tcp->tcp_rq;
17167 	struct tcp_options	*tcpopt;
17168 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17169 
17170 	/* socket options */
17171 	uint_t 			sopp_flags;
17172 	ssize_t			sopp_rxhiwat;
17173 	ssize_t			sopp_maxblk;
17174 	ushort_t		sopp_wroff;
17175 	ushort_t		sopp_tail;
17176 	ushort_t		sopp_copyopt;
17177 
17178 	tcpopt = (struct tcp_options *)mp->b_rptr;
17179 
17180 	/*
17181 	 * Drop the eager's ref on the listener, that was placed when
17182 	 * this eager began life in tcp_conn_request.
17183 	 */
17184 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17185 	if (IPCL_IS_NONSTR(connp)) {
17186 		/* Safe to free conn_ind message */
17187 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17188 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17189 	}
17190 
17191 	tcp->tcp_detached = B_FALSE;
17192 
17193 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17194 		/*
17195 		 * Someone blewoff the eager before we could finish
17196 		 * the accept.
17197 		 *
17198 		 * The only reason eager exists it because we put in
17199 		 * a ref on it when conn ind went up. We need to send
17200 		 * a disconnect indication up while the last reference
17201 		 * on the eager will be dropped by the squeue when we
17202 		 * return.
17203 		 */
17204 		ASSERT(tcp->tcp_listener == NULL);
17205 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17206 			if (IPCL_IS_NONSTR(connp)) {
17207 				ASSERT(tcp->tcp_issocket);
17208 				(*connp->conn_upcalls->su_disconnected)(
17209 				    connp->conn_upper_handle, tcp->tcp_connid,
17210 				    ECONNREFUSED);
17211 				freemsg(mp);
17212 			} else {
17213 				struct	T_discon_ind	*tdi;
17214 
17215 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17216 				/*
17217 				 * Let us reuse the incoming mblk to avoid
17218 				 * memory allocation failure problems. We know
17219 				 * that the size of the incoming mblk i.e.
17220 				 * stroptions is greater than sizeof
17221 				 * T_discon_ind. So the reallocb below can't
17222 				 * fail.
17223 				 */
17224 				freemsg(mp->b_cont);
17225 				mp->b_cont = NULL;
17226 				ASSERT(DB_REF(mp) == 1);
17227 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17228 				    B_FALSE);
17229 				ASSERT(mp != NULL);
17230 				DB_TYPE(mp) = M_PROTO;
17231 				((union T_primitives *)mp->b_rptr)->type =
17232 				    T_DISCON_IND;
17233 				tdi = (struct T_discon_ind *)mp->b_rptr;
17234 				if (tcp->tcp_issocket) {
17235 					tdi->DISCON_reason = ECONNREFUSED;
17236 					tdi->SEQ_number = 0;
17237 				} else {
17238 					tdi->DISCON_reason = ENOPROTOOPT;
17239 					tdi->SEQ_number =
17240 					    tcp->tcp_conn_req_seqnum;
17241 				}
17242 				mp->b_wptr = mp->b_rptr +
17243 				    sizeof (struct T_discon_ind);
17244 				putnext(q, mp);
17245 				return;
17246 			}
17247 		}
17248 		if (tcp->tcp_hard_binding) {
17249 			tcp->tcp_hard_binding = B_FALSE;
17250 			tcp->tcp_hard_bound = B_TRUE;
17251 		}
17252 		return;
17253 	}
17254 
17255 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17256 		int boundif = tcpopt->to_boundif;
17257 		uint_t len = sizeof (int);
17258 
17259 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17260 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17261 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17262 	}
17263 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17264 		uint_t on = 1;
17265 		uint_t len = sizeof (uint_t);
17266 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17267 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17268 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17269 	}
17270 
17271 	/*
17272 	 * Set max window size (tcp_recv_hiwater) of the acceptor.
17273 	 */
17274 	if (tcp->tcp_rcv_list == NULL) {
17275 		/*
17276 		 * Recv queue is empty, tcp_rwnd should not have changed.
17277 		 * That means it should be equal to the listener's tcp_rwnd.
17278 		 */
17279 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17280 	} else {
17281 #ifdef DEBUG
17282 		mblk_t *tmp;
17283 		mblk_t	*mp1;
17284 		uint_t	cnt = 0;
17285 
17286 		mp1 = tcp->tcp_rcv_list;
17287 		while ((tmp = mp1) != NULL) {
17288 			mp1 = tmp->b_next;
17289 			cnt += msgdsize(tmp);
17290 		}
17291 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17292 #endif
17293 		/* There is some data, add them back to get the max. */
17294 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17295 	}
17296 	/*
17297 	 * This is the first time we run on the correct
17298 	 * queue after tcp_accept. So fix all the q parameters
17299 	 * here.
17300 	 */
17301 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17302 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17303 
17304 	sopp_rxhiwat = tcp->tcp_fused ?
17305 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17306 	    tcp->tcp_recv_hiwater;
17307 
17308 	/*
17309 	 * Determine what write offset value to use depending on SACK and
17310 	 * whether the endpoint is fused or not.
17311 	 */
17312 	if (tcp->tcp_fused) {
17313 		ASSERT(tcp->tcp_loopback);
17314 		ASSERT(tcp->tcp_loopback_peer != NULL);
17315 		/*
17316 		 * For fused tcp loopback, set the stream head's write
17317 		 * offset value to zero since we won't be needing any room
17318 		 * for TCP/IP headers.  This would also improve performance
17319 		 * since it would reduce the amount of work done by kmem.
17320 		 * Non-fused tcp loopback case is handled separately below.
17321 		 */
17322 		sopp_wroff = 0;
17323 		/*
17324 		 * Update the peer's transmit parameters according to
17325 		 * our recently calculated high water mark value.
17326 		 */
17327 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17328 	} else if (tcp->tcp_snd_sack_ok) {
17329 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17330 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17331 	} else {
17332 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17333 		    tcps->tcps_wroff_xtra);
17334 	}
17335 
17336 	/*
17337 	 * If this is endpoint is handling SSL, then reserve extra
17338 	 * offset and space at the end.
17339 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17340 	 * overriding the previous setting. The extra cost of signing and
17341 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17342 	 * instead of a single contiguous one by the stream head
17343 	 * largely outweighs the statistical reduction of ACKs, when
17344 	 * applicable. The peer will also save on decryption and verification
17345 	 * costs.
17346 	 */
17347 	if (tcp->tcp_kssl_ctx != NULL) {
17348 		sopp_wroff += SSL3_WROFFSET;
17349 
17350 		sopp_flags |= SOCKOPT_TAIL;
17351 		sopp_tail = SSL3_MAX_TAIL_LEN;
17352 
17353 		sopp_flags |= SOCKOPT_ZCOPY;
17354 		sopp_copyopt = ZCVMUNSAFE;
17355 
17356 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
17357 	}
17358 
17359 	/* Send the options up */
17360 	if (IPCL_IS_NONSTR(connp)) {
17361 		struct sock_proto_props sopp;
17362 
17363 		sopp.sopp_flags = sopp_flags;
17364 		sopp.sopp_wroff = sopp_wroff;
17365 		sopp.sopp_maxblk = sopp_maxblk;
17366 		sopp.sopp_rxhiwat = sopp_rxhiwat;
17367 		if (sopp_flags & SOCKOPT_TAIL) {
17368 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17369 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
17370 			sopp.sopp_tail = sopp_tail;
17371 			sopp.sopp_zcopyflag = sopp_copyopt;
17372 		}
17373 		if (tcp->tcp_loopback) {
17374 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
17375 			sopp.sopp_loopback = B_TRUE;
17376 		}
17377 		(*connp->conn_upcalls->su_set_proto_props)
17378 		    (connp->conn_upper_handle, &sopp);
17379 	} else {
17380 		struct stroptions *stropt;
17381 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17382 		if (stropt_mp == NULL) {
17383 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
17384 			return;
17385 		}
17386 		DB_TYPE(stropt_mp) = M_SETOPTS;
17387 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17388 		stropt_mp->b_wptr += sizeof (struct stroptions);
17389 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
17390 		stropt->so_hiwat = sopp_rxhiwat;
17391 		stropt->so_wroff = sopp_wroff;
17392 		stropt->so_maxblk = sopp_maxblk;
17393 
17394 		if (sopp_flags & SOCKOPT_TAIL) {
17395 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17396 
17397 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
17398 			stropt->so_tail = sopp_tail;
17399 			stropt->so_copyopt = sopp_copyopt;
17400 		}
17401 
17402 		/* Send the options up */
17403 		putnext(q, stropt_mp);
17404 	}
17405 
17406 	freemsg(mp);
17407 	/*
17408 	 * Pass up any data and/or a fin that has been received.
17409 	 *
17410 	 * Adjust receive window in case it had decreased
17411 	 * (because there is data <=> tcp_rcv_list != NULL)
17412 	 * while the connection was detached. Note that
17413 	 * in case the eager was flow-controlled, w/o this
17414 	 * code, the rwnd may never open up again!
17415 	 */
17416 	if (tcp->tcp_rcv_list != NULL) {
17417 		if (IPCL_IS_NONSTR(connp)) {
17418 			mblk_t *mp;
17419 			int space_left;
17420 			int error;
17421 			boolean_t push = B_TRUE;
17422 
17423 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
17424 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
17425 			    &push) >= 0) {
17426 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17427 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17428 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17429 					tcp_xmit_ctl(NULL,
17430 					    tcp, (tcp->tcp_swnd == 0) ?
17431 					    tcp->tcp_suna : tcp->tcp_snxt,
17432 					    tcp->tcp_rnxt, TH_ACK);
17433 				}
17434 			}
17435 			while ((mp = tcp->tcp_rcv_list) != NULL) {
17436 				push = B_TRUE;
17437 				tcp->tcp_rcv_list = mp->b_next;
17438 				mp->b_next = NULL;
17439 				space_left = (*connp->conn_upcalls->su_recv)
17440 				    (connp->conn_upper_handle, mp, msgdsize(mp),
17441 				    0, &error, &push);
17442 				if (space_left < 0) {
17443 					/*
17444 					 * We should never be in middle of a
17445 					 * fallback, the squeue guarantees that.
17446 					 */
17447 					ASSERT(error != EOPNOTSUPP);
17448 				}
17449 			}
17450 			tcp->tcp_rcv_last_head = NULL;
17451 			tcp->tcp_rcv_last_tail = NULL;
17452 			tcp->tcp_rcv_cnt = 0;
17453 		} else {
17454 			/* We drain directly in case of fused tcp loopback */
17455 
17456 			if (!tcp->tcp_fused && canputnext(q)) {
17457 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17458 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17459 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17460 					tcp_xmit_ctl(NULL,
17461 					    tcp, (tcp->tcp_swnd == 0) ?
17462 					    tcp->tcp_suna : tcp->tcp_snxt,
17463 					    tcp->tcp_rnxt, TH_ACK);
17464 				}
17465 			}
17466 
17467 			(void) tcp_rcv_drain(tcp);
17468 		}
17469 
17470 		/*
17471 		 * For fused tcp loopback, back-enable peer endpoint
17472 		 * if it's currently flow-controlled.
17473 		 */
17474 		if (tcp->tcp_fused) {
17475 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17476 
17477 			ASSERT(peer_tcp != NULL);
17478 			ASSERT(peer_tcp->tcp_fused);
17479 
17480 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
17481 			if (peer_tcp->tcp_flow_stopped) {
17482 				tcp_clrqfull(peer_tcp);
17483 				TCP_STAT(tcps, tcp_fusion_backenabled);
17484 			}
17485 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17486 		}
17487 	}
17488 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17489 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17490 		tcp->tcp_ordrel_done = B_TRUE;
17491 		if (IPCL_IS_NONSTR(connp)) {
17492 			ASSERT(tcp->tcp_ordrel_mp == NULL);
17493 			(*connp->conn_upcalls->su_opctl)(
17494 			    connp->conn_upper_handle,
17495 			    SOCK_OPCTL_SHUT_RECV, 0);
17496 		} else {
17497 			mp = tcp->tcp_ordrel_mp;
17498 			tcp->tcp_ordrel_mp = NULL;
17499 			putnext(q, mp);
17500 		}
17501 	}
17502 	if (tcp->tcp_hard_binding) {
17503 		tcp->tcp_hard_binding = B_FALSE;
17504 		tcp->tcp_hard_bound = B_TRUE;
17505 	}
17506 
17507 	if (tcp->tcp_ka_enabled) {
17508 		tcp->tcp_ka_last_intrvl = 0;
17509 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17510 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17511 	}
17512 
17513 	/*
17514 	 * At this point, eager is fully established and will
17515 	 * have the following references -
17516 	 *
17517 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17518 	 * 1 reference for the squeue which will be dropped by the squeue as
17519 	 *	soon as this function returns.
17520 	 * There will be 1 additonal reference for being in classifier
17521 	 *	hash list provided something bad hasn't happened.
17522 	 */
17523 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17524 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17525 }
17526 
17527 /*
17528  * The function called through squeue to get behind listener's perimeter to
17529  * send a deffered conn_ind.
17530  */
17531 /* ARGSUSED */
17532 void
17533 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17534 {
17535 	conn_t	*connp = (conn_t *)arg;
17536 	tcp_t *listener = connp->conn_tcp;
17537 	struct T_conn_ind *conn_ind;
17538 	tcp_t *tcp;
17539 
17540 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
17541 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17542 	    conn_ind->OPT_length);
17543 
17544 	if (listener->tcp_state != TCPS_LISTEN) {
17545 		/*
17546 		 * If listener has closed, it would have caused a
17547 		 * a cleanup/blowoff to happen for the eager, so
17548 		 * we don't need to do anything more.
17549 		 */
17550 		freemsg(mp);
17551 		return;
17552 	}
17553 
17554 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
17555 }
17556 
17557 /* ARGSUSED */
17558 static int
17559 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
17560 {
17561 	tcp_t *listener, *eager;
17562 	mblk_t *opt_mp;
17563 	struct tcp_options *tcpopt;
17564 
17565 	listener = lconnp->conn_tcp;
17566 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17567 	eager = econnp->conn_tcp;
17568 	ASSERT(eager->tcp_listener != NULL);
17569 
17570 	ASSERT(eager->tcp_rq != NULL);
17571 
17572 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
17573 	if (opt_mp == NULL) {
17574 		return (-TPROTO);
17575 	}
17576 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
17577 	eager->tcp_issocket = B_TRUE;
17578 
17579 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17580 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17581 	ASSERT(econnp->conn_netstack ==
17582 	    listener->tcp_connp->conn_netstack);
17583 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
17584 
17585 	/* Put the ref for IP */
17586 	CONN_INC_REF(econnp);
17587 
17588 	/*
17589 	 * We should have minimum of 3 references on the conn
17590 	 * at this point. One each for TCP and IP and one for
17591 	 * the T_conn_ind that was sent up when the 3-way handshake
17592 	 * completed. In the normal case we would also have another
17593 	 * reference (making a total of 4) for the conn being in the
17594 	 * classifier hash list. However the eager could have received
17595 	 * an RST subsequently and tcp_closei_local could have removed
17596 	 * the eager from the classifier hash list, hence we can't
17597 	 * assert that reference.
17598 	 */
17599 	ASSERT(econnp->conn_ref >= 3);
17600 
17601 	opt_mp->b_datap->db_type = M_SETOPTS;
17602 	opt_mp->b_wptr += sizeof (struct tcp_options);
17603 
17604 	/*
17605 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17606 	 * from listener to acceptor.
17607 	 */
17608 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
17609 	tcpopt->to_flags = 0;
17610 
17611 	if (listener->tcp_bound_if != 0) {
17612 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
17613 		tcpopt->to_boundif = listener->tcp_bound_if;
17614 	}
17615 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17616 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
17617 	}
17618 
17619 	mutex_enter(&listener->tcp_eager_lock);
17620 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17621 
17622 		tcp_t *tail;
17623 		tcp_t *tcp;
17624 		mblk_t *mp1;
17625 
17626 		tcp = listener->tcp_eager_prev_q0;
17627 		/*
17628 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
17629 		 * deferred T_conn_ind queue. We need to get to the head
17630 		 * of the queue in order to send up T_conn_ind the same
17631 		 * order as how the 3WHS is completed.
17632 		 */
17633 		while (tcp != listener) {
17634 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17635 			    !tcp->tcp_kssl_pending)
17636 				break;
17637 			else
17638 				tcp = tcp->tcp_eager_prev_q0;
17639 		}
17640 		/* None of the pending eagers can be sent up now */
17641 		if (tcp == listener)
17642 			goto no_more_eagers;
17643 
17644 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17645 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17646 		/* Move from q0 to q */
17647 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17648 		listener->tcp_conn_req_cnt_q0--;
17649 		listener->tcp_conn_req_cnt_q++;
17650 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17651 		    tcp->tcp_eager_prev_q0;
17652 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17653 		    tcp->tcp_eager_next_q0;
17654 		tcp->tcp_eager_prev_q0 = NULL;
17655 		tcp->tcp_eager_next_q0 = NULL;
17656 		tcp->tcp_conn_def_q0 = B_FALSE;
17657 
17658 		/* Make sure the tcp isn't in the list of droppables */
17659 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
17660 		    tcp->tcp_eager_prev_drop_q0 == NULL);
17661 
17662 		/*
17663 		 * Insert at end of the queue because sockfs sends
17664 		 * down T_CONN_RES in chronological order. Leaving
17665 		 * the older conn indications at front of the queue
17666 		 * helps reducing search time.
17667 		 */
17668 		tail = listener->tcp_eager_last_q;
17669 		if (tail != NULL) {
17670 			tail->tcp_eager_next_q = tcp;
17671 		} else {
17672 			listener->tcp_eager_next_q = tcp;
17673 		}
17674 		listener->tcp_eager_last_q = tcp;
17675 		tcp->tcp_eager_next_q = NULL;
17676 
17677 		/* Need to get inside the listener perimeter */
17678 		CONN_INC_REF(listener->tcp_connp);
17679 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
17680 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
17681 		    SQTAG_TCP_SEND_PENDING);
17682 	}
17683 no_more_eagers:
17684 	tcp_eager_unlink(eager);
17685 	mutex_exit(&listener->tcp_eager_lock);
17686 
17687 	/*
17688 	 * At this point, the eager is detached from the listener
17689 	 * but we still have an extra refs on eager (apart from the
17690 	 * usual tcp references). The ref was placed in tcp_rput_data
17691 	 * before sending the conn_ind in tcp_send_conn_ind.
17692 	 * The ref will be dropped in tcp_accept_finish().
17693 	 */
17694 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
17695 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
17696 	return (0);
17697 }
17698 
17699 int
17700 tcp_accept(sock_lower_handle_t lproto_handle,
17701     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
17702     cred_t *cr)
17703 {
17704 	conn_t *lconnp, *econnp;
17705 	tcp_t *listener, *eager;
17706 	tcp_stack_t	*tcps;
17707 
17708 	lconnp = (conn_t *)lproto_handle;
17709 	listener = lconnp->conn_tcp;
17710 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17711 	econnp = (conn_t *)eproto_handle;
17712 	eager = econnp->conn_tcp;
17713 	ASSERT(eager->tcp_listener != NULL);
17714 	tcps = eager->tcp_tcps;
17715 
17716 	/*
17717 	 * It is OK to manipulate these fields outside the eager's squeue
17718 	 * because they will not start being used until tcp_accept_finish
17719 	 * has been called.
17720 	 */
17721 	ASSERT(lconnp->conn_upper_handle != NULL);
17722 	ASSERT(econnp->conn_upper_handle == NULL);
17723 	econnp->conn_upper_handle = sock_handle;
17724 	econnp->conn_upcalls = lconnp->conn_upcalls;
17725 	ASSERT(IPCL_IS_NONSTR(econnp));
17726 	/*
17727 	 * Create helper stream if it is a non-TPI TCP connection.
17728 	 */
17729 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
17730 		ip1dbg(("tcp_accept: create of IP helper stream"
17731 		    " failed\n"));
17732 		return (EPROTO);
17733 	}
17734 	eager->tcp_rq = econnp->conn_rq;
17735 	eager->tcp_wq = econnp->conn_wq;
17736 
17737 	ASSERT(eager->tcp_rq != NULL);
17738 
17739 	return (tcp_accept_common(lconnp, econnp, cr));
17740 }
17741 
17742 
17743 /*
17744  * This is the STREAMS entry point for T_CONN_RES coming down on
17745  * Acceptor STREAM when  sockfs listener does accept processing.
17746  * Read the block comment on top of tcp_conn_request().
17747  */
17748 void
17749 tcp_tpi_accept(queue_t *q, mblk_t *mp)
17750 {
17751 	queue_t *rq = RD(q);
17752 	struct T_conn_res *conn_res;
17753 	tcp_t *eager;
17754 	tcp_t *listener;
17755 	struct T_ok_ack *ok;
17756 	t_scalar_t PRIM_type;
17757 	conn_t *econnp;
17758 	cred_t *cr;
17759 
17760 	ASSERT(DB_TYPE(mp) == M_PROTO);
17761 
17762 	/*
17763 	 * All Solaris components should pass a db_credp
17764 	 * for this TPI message, hence we ASSERT.
17765 	 * But in case there is some other M_PROTO that looks
17766 	 * like a TPI message sent by some other kernel
17767 	 * component, we check and return an error.
17768 	 */
17769 	cr = msg_getcred(mp, NULL);
17770 	ASSERT(cr != NULL);
17771 	if (cr == NULL) {
17772 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
17773 		if (mp != NULL)
17774 			putnext(rq, mp);
17775 		return;
17776 	}
17777 	conn_res = (struct T_conn_res *)mp->b_rptr;
17778 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17779 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17780 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17781 		if (mp != NULL)
17782 			putnext(rq, mp);
17783 		return;
17784 	}
17785 	switch (conn_res->PRIM_type) {
17786 	case O_T_CONN_RES:
17787 	case T_CONN_RES:
17788 		/*
17789 		 * We pass up an err ack if allocb fails. This will
17790 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17791 		 * tcp_eager_blowoff to be called. sockfs will then call
17792 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17793 		 * we need to do the allocb up here because we have to
17794 		 * make sure rq->q_qinfo->qi_qclose still points to the
17795 		 * correct function (tcp_tpi_close_accept) in case allocb
17796 		 * fails.
17797 		 */
17798 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17799 		    &eager, conn_res->OPT_length);
17800 		PRIM_type = conn_res->PRIM_type;
17801 		mp->b_datap->db_type = M_PCPROTO;
17802 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17803 		ok = (struct T_ok_ack *)mp->b_rptr;
17804 		ok->PRIM_type = T_OK_ACK;
17805 		ok->CORRECT_prim = PRIM_type;
17806 		econnp = eager->tcp_connp;
17807 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
17808 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
17809 		eager->tcp_rq = rq;
17810 		eager->tcp_wq = q;
17811 		rq->q_ptr = econnp;
17812 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
17813 		q->q_ptr = econnp;
17814 		q->q_qinfo = &tcp_winit;
17815 		listener = eager->tcp_listener;
17816 
17817 		if (tcp_accept_common(listener->tcp_connp,
17818 		    econnp, cr) < 0) {
17819 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17820 			if (mp != NULL)
17821 				putnext(rq, mp);
17822 			return;
17823 		}
17824 
17825 		/*
17826 		 * Send the new local address also up to sockfs. There
17827 		 * should already be enough space in the mp that came
17828 		 * down from soaccept().
17829 		 */
17830 		if (eager->tcp_family == AF_INET) {
17831 			sin_t *sin;
17832 
17833 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17834 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17835 			sin = (sin_t *)mp->b_wptr;
17836 			mp->b_wptr += sizeof (sin_t);
17837 			sin->sin_family = AF_INET;
17838 			sin->sin_port = eager->tcp_lport;
17839 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17840 		} else {
17841 			sin6_t *sin6;
17842 
17843 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17844 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17845 			sin6 = (sin6_t *)mp->b_wptr;
17846 			mp->b_wptr += sizeof (sin6_t);
17847 			sin6->sin6_family = AF_INET6;
17848 			sin6->sin6_port = eager->tcp_lport;
17849 			if (eager->tcp_ipversion == IPV4_VERSION) {
17850 				sin6->sin6_flowinfo = 0;
17851 				IN6_IPADDR_TO_V4MAPPED(
17852 				    eager->tcp_ipha->ipha_src,
17853 				    &sin6->sin6_addr);
17854 			} else {
17855 				ASSERT(eager->tcp_ip6h != NULL);
17856 				sin6->sin6_flowinfo =
17857 				    eager->tcp_ip6h->ip6_vcf &
17858 				    ~IPV6_VERS_AND_FLOW_MASK;
17859 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17860 			}
17861 			sin6->sin6_scope_id = 0;
17862 			sin6->__sin6_src_id = 0;
17863 		}
17864 
17865 		putnext(rq, mp);
17866 		return;
17867 	default:
17868 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17869 		if (mp != NULL)
17870 			putnext(rq, mp);
17871 		return;
17872 	}
17873 }
17874 
17875 static int
17876 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17877 {
17878 	sin_t *sin = (sin_t *)sa;
17879 	sin6_t *sin6 = (sin6_t *)sa;
17880 
17881 	switch (tcp->tcp_family) {
17882 	case AF_INET:
17883 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17884 
17885 		if (*salenp < sizeof (sin_t))
17886 			return (EINVAL);
17887 
17888 		*sin = sin_null;
17889 		sin->sin_family = AF_INET;
17890 		if (tcp->tcp_state >= TCPS_BOUND) {
17891 			sin->sin_port = tcp->tcp_lport;
17892 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
17893 		}
17894 		*salenp = sizeof (sin_t);
17895 		break;
17896 
17897 	case AF_INET6:
17898 		if (*salenp < sizeof (sin6_t))
17899 			return (EINVAL);
17900 
17901 		*sin6 = sin6_null;
17902 		sin6->sin6_family = AF_INET6;
17903 		if (tcp->tcp_state >= TCPS_BOUND) {
17904 			sin6->sin6_port = tcp->tcp_lport;
17905 			mutex_enter(&tcp->tcp_connp->conn_lock);
17906 			if (tcp->tcp_ipversion == IPV4_VERSION) {
17907 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
17908 				    &sin6->sin6_addr);
17909 			} else {
17910 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
17911 			}
17912 			mutex_exit(&tcp->tcp_connp->conn_lock);
17913 		}
17914 		*salenp = sizeof (sin6_t);
17915 		break;
17916 	}
17917 
17918 	return (0);
17919 }
17920 
17921 static int
17922 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17923 {
17924 	sin_t *sin = (sin_t *)sa;
17925 	sin6_t *sin6 = (sin6_t *)sa;
17926 
17927 	if (tcp->tcp_state < TCPS_SYN_RCVD)
17928 		return (ENOTCONN);
17929 
17930 	switch (tcp->tcp_family) {
17931 	case AF_INET:
17932 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17933 
17934 		if (*salenp < sizeof (sin_t))
17935 			return (EINVAL);
17936 
17937 		*sin = sin_null;
17938 		sin->sin_family = AF_INET;
17939 		sin->sin_port = tcp->tcp_fport;
17940 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
17941 		    sin->sin_addr.s_addr);
17942 		*salenp = sizeof (sin_t);
17943 		break;
17944 
17945 	case AF_INET6:
17946 		if (*salenp < sizeof (sin6_t))
17947 			return (EINVAL);
17948 
17949 		*sin6 = sin6_null;
17950 		sin6->sin6_family = AF_INET6;
17951 		sin6->sin6_port = tcp->tcp_fport;
17952 		sin6->sin6_addr = tcp->tcp_remote_v6;
17953 		mutex_enter(&tcp->tcp_connp->conn_lock);
17954 		if (tcp->tcp_ipversion == IPV6_VERSION) {
17955 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
17956 			    ~IPV6_VERS_AND_FLOW_MASK;
17957 		}
17958 		mutex_exit(&tcp->tcp_connp->conn_lock);
17959 		*salenp = sizeof (sin6_t);
17960 		break;
17961 	}
17962 
17963 	return (0);
17964 }
17965 
17966 /*
17967  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
17968  */
17969 static void
17970 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
17971 {
17972 	void	*data;
17973 	mblk_t	*datamp = mp->b_cont;
17974 	tcp_t	*tcp = Q_TO_TCP(q);
17975 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
17976 
17977 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
17978 		cmdp->cb_error = EPROTO;
17979 		qreply(q, mp);
17980 		return;
17981 	}
17982 
17983 	data = datamp->b_rptr;
17984 
17985 	switch (cmdp->cb_cmd) {
17986 	case TI_GETPEERNAME:
17987 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
17988 		break;
17989 	case TI_GETMYNAME:
17990 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
17991 		break;
17992 	default:
17993 		cmdp->cb_error = EINVAL;
17994 		break;
17995 	}
17996 
17997 	qreply(q, mp);
17998 }
17999 
18000 void
18001 tcp_wput(queue_t *q, mblk_t *mp)
18002 {
18003 	conn_t	*connp = Q_TO_CONN(q);
18004 	tcp_t	*tcp;
18005 	void (*output_proc)();
18006 	t_scalar_t type;
18007 	uchar_t *rptr;
18008 	struct iocblk	*iocp;
18009 	size_t size;
18010 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18011 
18012 	ASSERT(connp->conn_ref >= 2);
18013 
18014 	switch (DB_TYPE(mp)) {
18015 	case M_DATA:
18016 		tcp = connp->conn_tcp;
18017 		ASSERT(tcp != NULL);
18018 
18019 		size = msgdsize(mp);
18020 
18021 		mutex_enter(&tcp->tcp_non_sq_lock);
18022 		tcp->tcp_squeue_bytes += size;
18023 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18024 			tcp_setqfull(tcp);
18025 		}
18026 		mutex_exit(&tcp->tcp_non_sq_lock);
18027 
18028 		CONN_INC_REF(connp);
18029 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18030 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18031 		return;
18032 
18033 	case M_CMD:
18034 		tcp_wput_cmdblk(q, mp);
18035 		return;
18036 
18037 	case M_PROTO:
18038 	case M_PCPROTO:
18039 		/*
18040 		 * if it is a snmp message, don't get behind the squeue
18041 		 */
18042 		tcp = connp->conn_tcp;
18043 		rptr = mp->b_rptr;
18044 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18045 			type = ((union T_primitives *)rptr)->type;
18046 		} else {
18047 			if (tcp->tcp_debug) {
18048 				(void) strlog(TCP_MOD_ID, 0, 1,
18049 				    SL_ERROR|SL_TRACE,
18050 				    "tcp_wput_proto, dropping one...");
18051 			}
18052 			freemsg(mp);
18053 			return;
18054 		}
18055 		if (type == T_SVR4_OPTMGMT_REQ) {
18056 			/*
18057 			 * All Solaris components should pass a db_credp
18058 			 * for this TPI message, hence we ASSERT.
18059 			 * But in case there is some other M_PROTO that looks
18060 			 * like a TPI message sent by some other kernel
18061 			 * component, we check and return an error.
18062 			 */
18063 			cred_t	*cr = msg_getcred(mp, NULL);
18064 
18065 			ASSERT(cr != NULL);
18066 			if (cr == NULL) {
18067 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18068 				return;
18069 			}
18070 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18071 			    cr)) {
18072 				/*
18073 				 * This was a SNMP request
18074 				 */
18075 				return;
18076 			} else {
18077 				output_proc = tcp_wput_proto;
18078 			}
18079 		} else {
18080 			output_proc = tcp_wput_proto;
18081 		}
18082 		break;
18083 	case M_IOCTL:
18084 		/*
18085 		 * Most ioctls can be processed right away without going via
18086 		 * squeues - process them right here. Those that do require
18087 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18088 		 * are processed by tcp_wput_ioctl().
18089 		 */
18090 		iocp = (struct iocblk *)mp->b_rptr;
18091 		tcp = connp->conn_tcp;
18092 
18093 		switch (iocp->ioc_cmd) {
18094 		case TCP_IOC_ABORT_CONN:
18095 			tcp_ioctl_abort_conn(q, mp);
18096 			return;
18097 		case TI_GETPEERNAME:
18098 		case TI_GETMYNAME:
18099 			mi_copyin(q, mp, NULL,
18100 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18101 			return;
18102 		case ND_SET:
18103 			/* nd_getset does the necessary checks */
18104 		case ND_GET:
18105 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18106 				CALL_IP_WPUT(connp, q, mp);
18107 				return;
18108 			}
18109 			qreply(q, mp);
18110 			return;
18111 		case TCP_IOC_DEFAULT_Q:
18112 			/*
18113 			 * Wants to be the default wq. Check the credentials
18114 			 * first, the rest is executed via squeue.
18115 			 */
18116 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18117 				iocp->ioc_error = EPERM;
18118 				iocp->ioc_count = 0;
18119 				mp->b_datap->db_type = M_IOCACK;
18120 				qreply(q, mp);
18121 				return;
18122 			}
18123 			output_proc = tcp_wput_ioctl;
18124 			break;
18125 		default:
18126 			output_proc = tcp_wput_ioctl;
18127 			break;
18128 		}
18129 		break;
18130 	default:
18131 		output_proc = tcp_wput_nondata;
18132 		break;
18133 	}
18134 
18135 	CONN_INC_REF(connp);
18136 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18137 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18138 }
18139 
18140 /*
18141  * Initial STREAMS write side put() procedure for sockets. It tries to
18142  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18143  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18144  * are handled by tcp_wput() as usual.
18145  *
18146  * All further messages will also be handled by tcp_wput() because we cannot
18147  * be sure that the above short cut is safe later.
18148  */
18149 static void
18150 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18151 {
18152 	conn_t			*connp = Q_TO_CONN(wq);
18153 	tcp_t			*tcp = connp->conn_tcp;
18154 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18155 
18156 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18157 	wq->q_qinfo = &tcp_winit;
18158 
18159 	ASSERT(IPCL_IS_TCP(connp));
18160 	ASSERT(TCP_IS_SOCKET(tcp));
18161 
18162 	if (DB_TYPE(mp) == M_PCPROTO &&
18163 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18164 	    car->PRIM_type == T_CAPABILITY_REQ) {
18165 		tcp_capability_req(tcp, mp);
18166 		return;
18167 	}
18168 
18169 	tcp_wput(wq, mp);
18170 }
18171 
18172 /* ARGSUSED */
18173 static void
18174 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18175 {
18176 #ifdef DEBUG
18177 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18178 #endif
18179 	freemsg(mp);
18180 }
18181 
18182 static boolean_t
18183 tcp_zcopy_check(tcp_t *tcp)
18184 {
18185 	conn_t	*connp = tcp->tcp_connp;
18186 	ire_t	*ire;
18187 	boolean_t	zc_enabled = B_FALSE;
18188 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18189 
18190 	if (do_tcpzcopy == 2)
18191 		zc_enabled = B_TRUE;
18192 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18193 	    IPCL_IS_CONNECTED(connp) &&
18194 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18195 	    connp->conn_dontroute == 0 &&
18196 	    !connp->conn_nexthop_set &&
18197 	    connp->conn_outgoing_ill == NULL &&
18198 	    do_tcpzcopy == 1) {
18199 		/*
18200 		 * the checks above  closely resemble the fast path checks
18201 		 * in tcp_send_data().
18202 		 */
18203 		mutex_enter(&connp->conn_lock);
18204 		ire = connp->conn_ire_cache;
18205 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18206 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18207 			IRE_REFHOLD(ire);
18208 			if (ire->ire_stq != NULL) {
18209 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18210 
18211 				zc_enabled = ill && (ill->ill_capabilities &
18212 				    ILL_CAPAB_ZEROCOPY) &&
18213 				    (ill->ill_zerocopy_capab->
18214 				    ill_zerocopy_flags != 0);
18215 			}
18216 			IRE_REFRELE(ire);
18217 		}
18218 		mutex_exit(&connp->conn_lock);
18219 	}
18220 	tcp->tcp_snd_zcopy_on = zc_enabled;
18221 	if (!TCP_IS_DETACHED(tcp)) {
18222 		if (zc_enabled) {
18223 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18224 			    ZCVMSAFE);
18225 			TCP_STAT(tcps, tcp_zcopy_on);
18226 		} else {
18227 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18228 			    ZCVMUNSAFE);
18229 			TCP_STAT(tcps, tcp_zcopy_off);
18230 		}
18231 	}
18232 	return (zc_enabled);
18233 }
18234 
18235 static mblk_t *
18236 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18237 {
18238 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18239 
18240 	if (do_tcpzcopy == 2)
18241 		return (bp);
18242 	else if (tcp->tcp_snd_zcopy_on) {
18243 		tcp->tcp_snd_zcopy_on = B_FALSE;
18244 		if (!TCP_IS_DETACHED(tcp)) {
18245 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18246 			    ZCVMUNSAFE);
18247 			TCP_STAT(tcps, tcp_zcopy_disable);
18248 		}
18249 	}
18250 	return (tcp_zcopy_backoff(tcp, bp, 0));
18251 }
18252 
18253 /*
18254  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18255  * the original desballoca'ed segmapped mblk.
18256  */
18257 static mblk_t *
18258 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18259 {
18260 	mblk_t *head, *tail, *nbp;
18261 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18262 
18263 	if (IS_VMLOANED_MBLK(bp)) {
18264 		TCP_STAT(tcps, tcp_zcopy_backoff);
18265 		if ((head = copyb(bp)) == NULL) {
18266 			/* fail to backoff; leave it for the next backoff */
18267 			tcp->tcp_xmit_zc_clean = B_FALSE;
18268 			return (bp);
18269 		}
18270 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18271 			if (fix_xmitlist)
18272 				tcp_zcopy_notify(tcp);
18273 			else
18274 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18275 		}
18276 		nbp = bp->b_cont;
18277 		if (fix_xmitlist) {
18278 			head->b_prev = bp->b_prev;
18279 			head->b_next = bp->b_next;
18280 			if (tcp->tcp_xmit_tail == bp)
18281 				tcp->tcp_xmit_tail = head;
18282 		}
18283 		bp->b_next = NULL;
18284 		bp->b_prev = NULL;
18285 		freeb(bp);
18286 	} else {
18287 		head = bp;
18288 		nbp = bp->b_cont;
18289 	}
18290 	tail = head;
18291 	while (nbp) {
18292 		if (IS_VMLOANED_MBLK(nbp)) {
18293 			TCP_STAT(tcps, tcp_zcopy_backoff);
18294 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18295 				tcp->tcp_xmit_zc_clean = B_FALSE;
18296 				tail->b_cont = nbp;
18297 				return (head);
18298 			}
18299 			tail = tail->b_cont;
18300 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18301 				if (fix_xmitlist)
18302 					tcp_zcopy_notify(tcp);
18303 				else
18304 					tail->b_datap->db_struioflag |=
18305 					    STRUIO_ZCNOTIFY;
18306 			}
18307 			bp = nbp;
18308 			nbp = nbp->b_cont;
18309 			if (fix_xmitlist) {
18310 				tail->b_prev = bp->b_prev;
18311 				tail->b_next = bp->b_next;
18312 				if (tcp->tcp_xmit_tail == bp)
18313 					tcp->tcp_xmit_tail = tail;
18314 			}
18315 			bp->b_next = NULL;
18316 			bp->b_prev = NULL;
18317 			freeb(bp);
18318 		} else {
18319 			tail->b_cont = nbp;
18320 			tail = nbp;
18321 			nbp = nbp->b_cont;
18322 		}
18323 	}
18324 	if (fix_xmitlist) {
18325 		tcp->tcp_xmit_last = tail;
18326 		tcp->tcp_xmit_zc_clean = B_TRUE;
18327 	}
18328 	return (head);
18329 }
18330 
18331 static void
18332 tcp_zcopy_notify(tcp_t *tcp)
18333 {
18334 	struct stdata	*stp;
18335 	conn_t *connp;
18336 
18337 	if (tcp->tcp_detached)
18338 		return;
18339 	connp = tcp->tcp_connp;
18340 	if (IPCL_IS_NONSTR(connp)) {
18341 		(*connp->conn_upcalls->su_zcopy_notify)
18342 		    (connp->conn_upper_handle);
18343 		return;
18344 	}
18345 	stp = STREAM(tcp->tcp_rq);
18346 	mutex_enter(&stp->sd_lock);
18347 	stp->sd_flag |= STZCNOTIFY;
18348 	cv_broadcast(&stp->sd_zcopy_wait);
18349 	mutex_exit(&stp->sd_lock);
18350 }
18351 
18352 static boolean_t
18353 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18354 {
18355 	ire_t	*ire;
18356 	conn_t	*connp = tcp->tcp_connp;
18357 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18358 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18359 
18360 	mutex_enter(&connp->conn_lock);
18361 	ire = connp->conn_ire_cache;
18362 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18363 
18364 	if ((ire != NULL) &&
18365 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18366 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18367 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18368 		IRE_REFHOLD(ire);
18369 		mutex_exit(&connp->conn_lock);
18370 	} else {
18371 		boolean_t cached = B_FALSE;
18372 		ts_label_t *tsl;
18373 
18374 		/* force a recheck later on */
18375 		tcp->tcp_ire_ill_check_done = B_FALSE;
18376 
18377 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18378 		connp->conn_ire_cache = NULL;
18379 		mutex_exit(&connp->conn_lock);
18380 
18381 		if (ire != NULL)
18382 			IRE_REFRELE_NOTR(ire);
18383 
18384 		tsl = crgetlabel(CONN_CRED(connp));
18385 		ire = (dst ?
18386 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18387 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18388 		    connp->conn_zoneid, tsl, ipst));
18389 
18390 		if (ire == NULL) {
18391 			TCP_STAT(tcps, tcp_ire_null);
18392 			return (B_FALSE);
18393 		}
18394 
18395 		IRE_REFHOLD_NOTR(ire);
18396 
18397 		mutex_enter(&connp->conn_lock);
18398 		if (CONN_CACHE_IRE(connp)) {
18399 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18400 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18401 				TCP_CHECK_IREINFO(tcp, ire);
18402 				connp->conn_ire_cache = ire;
18403 				cached = B_TRUE;
18404 			}
18405 			rw_exit(&ire->ire_bucket->irb_lock);
18406 		}
18407 		mutex_exit(&connp->conn_lock);
18408 
18409 		/*
18410 		 * We can continue to use the ire but since it was
18411 		 * not cached, we should drop the extra reference.
18412 		 */
18413 		if (!cached)
18414 			IRE_REFRELE_NOTR(ire);
18415 
18416 		/*
18417 		 * Rampart note: no need to select a new label here, since
18418 		 * labels are not allowed to change during the life of a TCP
18419 		 * connection.
18420 		 */
18421 	}
18422 
18423 	*irep = ire;
18424 
18425 	return (B_TRUE);
18426 }
18427 
18428 /*
18429  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18430  *
18431  * 0 = success;
18432  * 1 = failed to find ire and ill.
18433  */
18434 static boolean_t
18435 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18436 {
18437 	ipha_t		*ipha;
18438 	ipaddr_t	dst;
18439 	ire_t		*ire;
18440 	ill_t		*ill;
18441 	mblk_t		*ire_fp_mp;
18442 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18443 
18444 	if (mp != NULL)
18445 		ipha = (ipha_t *)mp->b_rptr;
18446 	else
18447 		ipha = tcp->tcp_ipha;
18448 	dst = ipha->ipha_dst;
18449 
18450 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18451 		return (B_FALSE);
18452 
18453 	if ((ire->ire_flags & RTF_MULTIRT) ||
18454 	    (ire->ire_stq == NULL) ||
18455 	    (ire->ire_nce == NULL) ||
18456 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18457 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18458 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18459 		TCP_STAT(tcps, tcp_ip_ire_send);
18460 		IRE_REFRELE(ire);
18461 		return (B_FALSE);
18462 	}
18463 
18464 	ill = ire_to_ill(ire);
18465 	ASSERT(ill != NULL);
18466 
18467 	if (!tcp->tcp_ire_ill_check_done) {
18468 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18469 		tcp->tcp_ire_ill_check_done = B_TRUE;
18470 	}
18471 
18472 	*irep = ire;
18473 	*illp = ill;
18474 
18475 	return (B_TRUE);
18476 }
18477 
18478 static void
18479 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18480 {
18481 	ipha_t		*ipha;
18482 	ipaddr_t	src;
18483 	ipaddr_t	dst;
18484 	uint32_t	cksum;
18485 	ire_t		*ire;
18486 	uint16_t	*up;
18487 	ill_t		*ill;
18488 	conn_t		*connp = tcp->tcp_connp;
18489 	uint32_t	hcksum_txflags = 0;
18490 	mblk_t		*ire_fp_mp;
18491 	uint_t		ire_fp_mp_len;
18492 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18493 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18494 	cred_t		*cr;
18495 	pid_t		cpid;
18496 
18497 	ASSERT(DB_TYPE(mp) == M_DATA);
18498 
18499 	/*
18500 	 * Here we need to handle the overloading of the cred_t for
18501 	 * both getpeerucred and TX.
18502 	 * If this is a SYN then the caller already set db_credp so
18503 	 * that getpeerucred will work. But if TX is in use we might have
18504 	 * a conn_effective_cred which is different, and we need to use that
18505 	 * cred to make TX use the correct label and label dependent route.
18506 	 */
18507 	if (is_system_labeled()) {
18508 		cr = msg_getcred(mp, &cpid);
18509 		if (cr == NULL || connp->conn_effective_cred != NULL)
18510 			mblk_setcred(mp, CONN_CRED(connp), cpid);
18511 	}
18512 
18513 	ipha = (ipha_t *)mp->b_rptr;
18514 	src = ipha->ipha_src;
18515 	dst = ipha->ipha_dst;
18516 
18517 	ASSERT(q != NULL);
18518 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
18519 
18520 	/*
18521 	 * Drop off fast path for IPv6 and also if options are present or
18522 	 * we need to resolve a TS label.
18523 	 */
18524 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18525 	    !IPCL_IS_CONNECTED(connp) ||
18526 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18527 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18528 	    !connp->conn_ulp_labeled ||
18529 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18530 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18531 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18532 		if (tcp->tcp_snd_zcopy_aware)
18533 			mp = tcp_zcopy_disable(tcp, mp);
18534 		TCP_STAT(tcps, tcp_ip_send);
18535 		CALL_IP_WPUT(connp, q, mp);
18536 		return;
18537 	}
18538 
18539 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18540 		if (tcp->tcp_snd_zcopy_aware)
18541 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18542 		CALL_IP_WPUT(connp, q, mp);
18543 		return;
18544 	}
18545 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18546 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18547 
18548 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18549 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18550 #ifndef _BIG_ENDIAN
18551 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18552 #endif
18553 
18554 	/*
18555 	 * Check to see if we need to re-enable LSO/MDT for this connection
18556 	 * because it was previously disabled due to changes in the ill;
18557 	 * note that by doing it here, this re-enabling only applies when
18558 	 * the packet is not dispatched through CALL_IP_WPUT().
18559 	 *
18560 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18561 	 * case, since that's how we ended up here.  For IPv6, we do the
18562 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18563 	 */
18564 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18565 		/*
18566 		 * Restore LSO for this connection, so that next time around
18567 		 * it is eligible to go through tcp_lsosend() path again.
18568 		 */
18569 		TCP_STAT(tcps, tcp_lso_enabled);
18570 		tcp->tcp_lso = B_TRUE;
18571 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18572 		    "interface %s\n", (void *)connp, ill->ill_name));
18573 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18574 		/*
18575 		 * Restore MDT for this connection, so that next time around
18576 		 * it is eligible to go through tcp_multisend() path again.
18577 		 */
18578 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18579 		tcp->tcp_mdt = B_TRUE;
18580 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18581 		    "interface %s\n", (void *)connp, ill->ill_name));
18582 	}
18583 
18584 	if (tcp->tcp_snd_zcopy_aware) {
18585 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18586 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18587 			mp = tcp_zcopy_disable(tcp, mp);
18588 		/*
18589 		 * we shouldn't need to reset ipha as the mp containing
18590 		 * ipha should never be a zero-copy mp.
18591 		 */
18592 	}
18593 
18594 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18595 		ASSERT(ill->ill_hcksum_capab != NULL);
18596 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18597 	}
18598 
18599 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18600 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18601 
18602 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18603 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18604 
18605 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18606 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18607 
18608 	/* Software checksum? */
18609 	if (DB_CKSUMFLAGS(mp) == 0) {
18610 		TCP_STAT(tcps, tcp_out_sw_cksum);
18611 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18612 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18613 	}
18614 
18615 	/* Calculate IP header checksum if hardware isn't capable */
18616 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18617 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18618 		    ((uint16_t *)ipha)[4]);
18619 	}
18620 
18621 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18622 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18623 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18624 
18625 	UPDATE_OB_PKT_COUNT(ire);
18626 	ire->ire_last_used_time = lbolt;
18627 
18628 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18629 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18630 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18631 	    ntohs(ipha->ipha_length));
18632 
18633 	DTRACE_PROBE4(ip4__physical__out__start,
18634 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
18635 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
18636 	    ipst->ips_ipv4firewall_physical_out,
18637 	    NULL, ill, ipha, mp, mp, 0, ipst);
18638 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18639 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
18640 
18641 	if (mp != NULL) {
18642 		if (ipst->ips_ipobs_enabled) {
18643 			zoneid_t szone;
18644 
18645 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
18646 			    ipst, ALL_ZONES);
18647 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
18648 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
18649 		}
18650 
18651 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
18652 	}
18653 
18654 	IRE_REFRELE(ire);
18655 }
18656 
18657 /*
18658  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18659  * if the receiver shrinks the window, i.e. moves the right window to the
18660  * left, the we should not send new data, but should retransmit normally the
18661  * old unacked data between suna and suna + swnd. We might has sent data
18662  * that is now outside the new window, pretend that we didn't send  it.
18663  */
18664 static void
18665 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18666 {
18667 	uint32_t	snxt = tcp->tcp_snxt;
18668 
18669 	ASSERT(shrunk_count > 0);
18670 
18671 	if (!tcp->tcp_is_wnd_shrnk) {
18672 		tcp->tcp_snxt_shrunk = snxt;
18673 		tcp->tcp_is_wnd_shrnk = B_TRUE;
18674 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
18675 		tcp->tcp_snxt_shrunk = snxt;
18676 	}
18677 
18678 	/* Pretend we didn't send the data outside the window */
18679 	snxt -= shrunk_count;
18680 
18681 	/* Reset all the values per the now shrunk window */
18682 	tcp_update_xmit_tail(tcp, snxt);
18683 	tcp->tcp_unsent += shrunk_count;
18684 
18685 	/*
18686 	 * If the SACK option is set, delete the entire list of
18687 	 * notsack'ed blocks.
18688 	 */
18689 	if (tcp->tcp_sack_info != NULL) {
18690 		if (tcp->tcp_notsack_list != NULL)
18691 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
18692 	}
18693 
18694 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18695 		/*
18696 		 * Make sure the timer is running so that we will probe a zero
18697 		 * window.
18698 		 */
18699 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18700 }
18701 
18702 
18703 /*
18704  * The TCP normal data output path.
18705  * NOTE: the logic of the fast path is duplicated from this function.
18706  */
18707 static void
18708 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18709 {
18710 	int		len;
18711 	mblk_t		*local_time;
18712 	mblk_t		*mp1;
18713 	uint32_t	snxt;
18714 	int		tail_unsent;
18715 	int		tcpstate;
18716 	int		usable = 0;
18717 	mblk_t		*xmit_tail;
18718 	queue_t		*q = tcp->tcp_wq;
18719 	int32_t		mss;
18720 	int32_t		num_sack_blk = 0;
18721 	int32_t		tcp_hdr_len;
18722 	int32_t		tcp_tcp_hdr_len;
18723 	int		mdt_thres;
18724 	int		rc;
18725 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18726 	ip_stack_t	*ipst;
18727 
18728 	tcpstate = tcp->tcp_state;
18729 	if (mp == NULL) {
18730 		/*
18731 		 * tcp_wput_data() with NULL mp should only be called when
18732 		 * there is unsent data.
18733 		 */
18734 		ASSERT(tcp->tcp_unsent > 0);
18735 		/* Really tacky... but we need this for detached closes. */
18736 		len = tcp->tcp_unsent;
18737 		goto data_null;
18738 	}
18739 
18740 #if CCS_STATS
18741 	wrw_stats.tot.count++;
18742 	wrw_stats.tot.bytes += msgdsize(mp);
18743 #endif
18744 	ASSERT(mp->b_datap->db_type == M_DATA);
18745 	/*
18746 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18747 	 * or before a connection attempt has begun.
18748 	 */
18749 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18750 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18751 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18752 #ifdef DEBUG
18753 			cmn_err(CE_WARN,
18754 			    "tcp_wput_data: data after ordrel, %s",
18755 			    tcp_display(tcp, NULL,
18756 			    DISP_ADDR_AND_PORT));
18757 #else
18758 			if (tcp->tcp_debug) {
18759 				(void) strlog(TCP_MOD_ID, 0, 1,
18760 				    SL_TRACE|SL_ERROR,
18761 				    "tcp_wput_data: data after ordrel, %s\n",
18762 				    tcp_display(tcp, NULL,
18763 				    DISP_ADDR_AND_PORT));
18764 			}
18765 #endif /* DEBUG */
18766 		}
18767 		if (tcp->tcp_snd_zcopy_aware &&
18768 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18769 			tcp_zcopy_notify(tcp);
18770 		freemsg(mp);
18771 		mutex_enter(&tcp->tcp_non_sq_lock);
18772 		if (tcp->tcp_flow_stopped &&
18773 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18774 			tcp_clrqfull(tcp);
18775 		}
18776 		mutex_exit(&tcp->tcp_non_sq_lock);
18777 		return;
18778 	}
18779 
18780 	/* Strip empties */
18781 	for (;;) {
18782 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18783 		    (uintptr_t)INT_MAX);
18784 		len = (int)(mp->b_wptr - mp->b_rptr);
18785 		if (len > 0)
18786 			break;
18787 		mp1 = mp;
18788 		mp = mp->b_cont;
18789 		freeb(mp1);
18790 		if (!mp) {
18791 			return;
18792 		}
18793 	}
18794 
18795 	/* If we are the first on the list ... */
18796 	if (tcp->tcp_xmit_head == NULL) {
18797 		tcp->tcp_xmit_head = mp;
18798 		tcp->tcp_xmit_tail = mp;
18799 		tcp->tcp_xmit_tail_unsent = len;
18800 	} else {
18801 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18802 		struct datab *dp;
18803 
18804 		mp1 = tcp->tcp_xmit_last;
18805 		if (len < tcp_tx_pull_len &&
18806 		    (dp = mp1->b_datap)->db_ref == 1 &&
18807 		    dp->db_lim - mp1->b_wptr >= len) {
18808 			ASSERT(len > 0);
18809 			ASSERT(!mp1->b_cont);
18810 			if (len == 1) {
18811 				*mp1->b_wptr++ = *mp->b_rptr;
18812 			} else {
18813 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18814 				mp1->b_wptr += len;
18815 			}
18816 			if (mp1 == tcp->tcp_xmit_tail)
18817 				tcp->tcp_xmit_tail_unsent += len;
18818 			mp1->b_cont = mp->b_cont;
18819 			if (tcp->tcp_snd_zcopy_aware &&
18820 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18821 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18822 			freeb(mp);
18823 			mp = mp1;
18824 		} else {
18825 			tcp->tcp_xmit_last->b_cont = mp;
18826 		}
18827 		len += tcp->tcp_unsent;
18828 	}
18829 
18830 	/* Tack on however many more positive length mblks we have */
18831 	if ((mp1 = mp->b_cont) != NULL) {
18832 		do {
18833 			int tlen;
18834 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18835 			    (uintptr_t)INT_MAX);
18836 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18837 			if (tlen <= 0) {
18838 				mp->b_cont = mp1->b_cont;
18839 				freeb(mp1);
18840 			} else {
18841 				len += tlen;
18842 				mp = mp1;
18843 			}
18844 		} while ((mp1 = mp->b_cont) != NULL);
18845 	}
18846 	tcp->tcp_xmit_last = mp;
18847 	tcp->tcp_unsent = len;
18848 
18849 	if (urgent)
18850 		usable = 1;
18851 
18852 data_null:
18853 	snxt = tcp->tcp_snxt;
18854 	xmit_tail = tcp->tcp_xmit_tail;
18855 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18856 
18857 	/*
18858 	 * Note that tcp_mss has been adjusted to take into account the
18859 	 * timestamp option if applicable.  Because SACK options do not
18860 	 * appear in every TCP segments and they are of variable lengths,
18861 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18862 	 * the actual segment length when we need to send a segment which
18863 	 * includes SACK options.
18864 	 */
18865 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18866 		int32_t	opt_len;
18867 
18868 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18869 		    tcp->tcp_num_sack_blk);
18870 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18871 		    2 + TCPOPT_HEADER_LEN;
18872 		mss = tcp->tcp_mss - opt_len;
18873 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18874 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18875 	} else {
18876 		mss = tcp->tcp_mss;
18877 		tcp_hdr_len = tcp->tcp_hdr_len;
18878 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18879 	}
18880 
18881 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18882 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18883 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18884 	}
18885 	if (tcpstate == TCPS_SYN_RCVD) {
18886 		/*
18887 		 * The three-way connection establishment handshake is not
18888 		 * complete yet. We want to queue the data for transmission
18889 		 * after entering ESTABLISHED state (RFC793). A jump to
18890 		 * "done" label effectively leaves data on the queue.
18891 		 */
18892 		goto done;
18893 	} else {
18894 		int usable_r;
18895 
18896 		/*
18897 		 * In the special case when cwnd is zero, which can only
18898 		 * happen if the connection is ECN capable, return now.
18899 		 * New segments is sent using tcp_timer().  The timer
18900 		 * is set in tcp_rput_data().
18901 		 */
18902 		if (tcp->tcp_cwnd == 0) {
18903 			/*
18904 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18905 			 * finished.
18906 			 */
18907 			ASSERT(tcp->tcp_ecn_ok ||
18908 			    tcp->tcp_state < TCPS_ESTABLISHED);
18909 			return;
18910 		}
18911 
18912 		/* NOTE: trouble if xmitting while SYN not acked? */
18913 		usable_r = snxt - tcp->tcp_suna;
18914 		usable_r = tcp->tcp_swnd - usable_r;
18915 
18916 		/*
18917 		 * Check if the receiver has shrunk the window.  If
18918 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18919 		 * cannot be set as there is unsent data, so FIN cannot
18920 		 * be sent out.  Otherwise, we need to take into account
18921 		 * of FIN as it consumes an "invisible" sequence number.
18922 		 */
18923 		ASSERT(tcp->tcp_fin_sent == 0);
18924 		if (usable_r < 0) {
18925 			/*
18926 			 * The receiver has shrunk the window and we have sent
18927 			 * -usable_r date beyond the window, re-adjust.
18928 			 *
18929 			 * If TCP window scaling is enabled, there can be
18930 			 * round down error as the advertised receive window
18931 			 * is actually right shifted n bits.  This means that
18932 			 * the lower n bits info is wiped out.  It will look
18933 			 * like the window is shrunk.  Do a check here to
18934 			 * see if the shrunk amount is actually within the
18935 			 * error in window calculation.  If it is, just
18936 			 * return.  Note that this check is inside the
18937 			 * shrunk window check.  This makes sure that even
18938 			 * though tcp_process_shrunk_swnd() is not called,
18939 			 * we will stop further processing.
18940 			 */
18941 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18942 				tcp_process_shrunk_swnd(tcp, -usable_r);
18943 			}
18944 			return;
18945 		}
18946 
18947 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18948 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18949 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18950 
18951 		/* usable = MIN(usable, unsent) */
18952 		if (usable_r > len)
18953 			usable_r = len;
18954 
18955 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18956 		if (usable_r > 0) {
18957 			usable = usable_r;
18958 		} else {
18959 			/* Bypass all other unnecessary processing. */
18960 			goto done;
18961 		}
18962 	}
18963 
18964 	local_time = (mblk_t *)lbolt;
18965 
18966 	/*
18967 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18968 	 * BSD.  This is more in line with the true intent of Nagle.
18969 	 *
18970 	 * The conditions are:
18971 	 * 1. The amount of unsent data (or amount of data which can be
18972 	 *    sent, whichever is smaller) is less than Nagle limit.
18973 	 * 2. The last sent size is also less than Nagle limit.
18974 	 * 3. There is unack'ed data.
18975 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18976 	 *    Nagle algorithm.  This reduces the probability that urgent
18977 	 *    bytes get "merged" together.
18978 	 * 5. The app has not closed the connection.  This eliminates the
18979 	 *    wait time of the receiving side waiting for the last piece of
18980 	 *    (small) data.
18981 	 *
18982 	 * If all are satisified, exit without sending anything.  Note
18983 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18984 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18985 	 * 4095).
18986 	 */
18987 	if (usable < (int)tcp->tcp_naglim &&
18988 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18989 	    snxt != tcp->tcp_suna &&
18990 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18991 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18992 		goto done;
18993 	}
18994 
18995 	/*
18996 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
18997 	 * is set, then we have to force TCP not to send partial segment
18998 	 * (smaller than MSS bytes). We are calculating the usable now
18999 	 * based on full mss and will save the rest of remaining data for
19000 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
19001 	 * something to do zero window probe.
19002 	 */
19003 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
19004 		if (usable < mss)
19005 			goto done;
19006 		usable = (usable / mss) * mss;
19007 	}
19008 
19009 	/* Update the latest receive window size in TCP header. */
19010 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19011 	    tcp->tcp_tcph->th_win);
19012 
19013 	/*
19014 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19015 	 *
19016 	 * 1. Simple TCP/IP{v4,v6} (no options).
19017 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19018 	 * 3. If the TCP connection is in ESTABLISHED state.
19019 	 * 4. The TCP is not detached.
19020 	 *
19021 	 * If any of the above conditions have changed during the
19022 	 * connection, stop using LSO/MDT and restore the stream head
19023 	 * parameters accordingly.
19024 	 */
19025 	ipst = tcps->tcps_netstack->netstack_ip;
19026 
19027 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19028 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19029 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19030 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19031 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19032 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19033 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19034 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19035 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19036 		if (tcp->tcp_lso) {
19037 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19038 			tcp->tcp_lso = B_FALSE;
19039 		} else {
19040 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19041 			tcp->tcp_mdt = B_FALSE;
19042 		}
19043 
19044 		/* Anything other than detached is considered pathological */
19045 		if (!TCP_IS_DETACHED(tcp)) {
19046 			if (tcp->tcp_lso)
19047 				TCP_STAT(tcps, tcp_lso_disabled);
19048 			else
19049 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19050 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19051 		}
19052 	}
19053 
19054 	/* Use MDT if sendable amount is greater than the threshold */
19055 	if (tcp->tcp_mdt &&
19056 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19057 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19058 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19059 	    (tcp->tcp_valid_bits == 0 ||
19060 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19061 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19062 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19063 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19064 		    local_time, mdt_thres);
19065 	} else {
19066 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19067 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19068 		    local_time, INT_MAX);
19069 	}
19070 
19071 	/* Pretend that all we were trying to send really got sent */
19072 	if (rc < 0 && tail_unsent < 0) {
19073 		do {
19074 			xmit_tail = xmit_tail->b_cont;
19075 			xmit_tail->b_prev = local_time;
19076 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19077 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19078 			tail_unsent += (int)(xmit_tail->b_wptr -
19079 			    xmit_tail->b_rptr);
19080 		} while (tail_unsent < 0);
19081 	}
19082 done:;
19083 	tcp->tcp_xmit_tail = xmit_tail;
19084 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19085 	len = tcp->tcp_snxt - snxt;
19086 	if (len) {
19087 		/*
19088 		 * If new data was sent, need to update the notsack
19089 		 * list, which is, afterall, data blocks that have
19090 		 * not been sack'ed by the receiver.  New data is
19091 		 * not sack'ed.
19092 		 */
19093 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19094 			/* len is a negative value. */
19095 			tcp->tcp_pipe -= len;
19096 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19097 			    tcp->tcp_snxt, snxt,
19098 			    &(tcp->tcp_num_notsack_blk),
19099 			    &(tcp->tcp_cnt_notsack_list));
19100 		}
19101 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19102 		tcp->tcp_rack = tcp->tcp_rnxt;
19103 		tcp->tcp_rack_cnt = 0;
19104 		if ((snxt + len) == tcp->tcp_suna) {
19105 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19106 		}
19107 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19108 		/*
19109 		 * Didn't send anything. Make sure the timer is running
19110 		 * so that we will probe a zero window.
19111 		 */
19112 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19113 	}
19114 	/* Note that len is the amount we just sent but with a negative sign */
19115 	tcp->tcp_unsent += len;
19116 	mutex_enter(&tcp->tcp_non_sq_lock);
19117 	if (tcp->tcp_flow_stopped) {
19118 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19119 			tcp_clrqfull(tcp);
19120 		}
19121 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19122 		tcp_setqfull(tcp);
19123 	}
19124 	mutex_exit(&tcp->tcp_non_sq_lock);
19125 }
19126 
19127 /*
19128  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19129  * outgoing TCP header with the template header, as well as other
19130  * options such as time-stamp, ECN and/or SACK.
19131  */
19132 static void
19133 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19134 {
19135 	tcph_t *tcp_tmpl, *tcp_h;
19136 	uint32_t *dst, *src;
19137 	int hdrlen;
19138 
19139 	ASSERT(OK_32PTR(rptr));
19140 
19141 	/* Template header */
19142 	tcp_tmpl = tcp->tcp_tcph;
19143 
19144 	/* Header of outgoing packet */
19145 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19146 
19147 	/* dst and src are opaque 32-bit fields, used for copying */
19148 	dst = (uint32_t *)rptr;
19149 	src = (uint32_t *)tcp->tcp_iphc;
19150 	hdrlen = tcp->tcp_hdr_len;
19151 
19152 	/* Fill time-stamp option if needed */
19153 	if (tcp->tcp_snd_ts_ok) {
19154 		U32_TO_BE32((uint32_t)now,
19155 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19156 		U32_TO_BE32(tcp->tcp_ts_recent,
19157 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19158 	} else {
19159 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19160 	}
19161 
19162 	/*
19163 	 * Copy the template header; is this really more efficient than
19164 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19165 	 * but perhaps not for other scenarios.
19166 	 */
19167 	dst[0] = src[0];
19168 	dst[1] = src[1];
19169 	dst[2] = src[2];
19170 	dst[3] = src[3];
19171 	dst[4] = src[4];
19172 	dst[5] = src[5];
19173 	dst[6] = src[6];
19174 	dst[7] = src[7];
19175 	dst[8] = src[8];
19176 	dst[9] = src[9];
19177 	if (hdrlen -= 40) {
19178 		hdrlen >>= 2;
19179 		dst += 10;
19180 		src += 10;
19181 		do {
19182 			*dst++ = *src++;
19183 		} while (--hdrlen);
19184 	}
19185 
19186 	/*
19187 	 * Set the ECN info in the TCP header if it is not a zero
19188 	 * window probe.  Zero window probe is only sent in
19189 	 * tcp_wput_data() and tcp_timer().
19190 	 */
19191 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19192 		SET_ECT(tcp, rptr);
19193 
19194 		if (tcp->tcp_ecn_echo_on)
19195 			tcp_h->th_flags[0] |= TH_ECE;
19196 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19197 			tcp_h->th_flags[0] |= TH_CWR;
19198 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19199 		}
19200 	}
19201 
19202 	/* Fill in SACK options */
19203 	if (num_sack_blk > 0) {
19204 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19205 		sack_blk_t *tmp;
19206 		int32_t	i;
19207 
19208 		wptr[0] = TCPOPT_NOP;
19209 		wptr[1] = TCPOPT_NOP;
19210 		wptr[2] = TCPOPT_SACK;
19211 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19212 		    sizeof (sack_blk_t);
19213 		wptr += TCPOPT_REAL_SACK_LEN;
19214 
19215 		tmp = tcp->tcp_sack_list;
19216 		for (i = 0; i < num_sack_blk; i++) {
19217 			U32_TO_BE32(tmp[i].begin, wptr);
19218 			wptr += sizeof (tcp_seq);
19219 			U32_TO_BE32(tmp[i].end, wptr);
19220 			wptr += sizeof (tcp_seq);
19221 		}
19222 		tcp_h->th_offset_and_rsrvd[0] +=
19223 		    ((num_sack_blk * 2 + 1) << 4);
19224 	}
19225 }
19226 
19227 /*
19228  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19229  * the destination address and SAP attribute, and if necessary, the
19230  * hardware checksum offload attribute to a Multidata message.
19231  */
19232 static int
19233 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19234     const uint32_t start, const uint32_t stuff, const uint32_t end,
19235     const uint32_t flags, tcp_stack_t *tcps)
19236 {
19237 	/* Add global destination address & SAP attribute */
19238 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19239 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19240 		    "destination address+SAP\n"));
19241 
19242 		if (dlmp != NULL)
19243 			TCP_STAT(tcps, tcp_mdt_allocfail);
19244 		return (-1);
19245 	}
19246 
19247 	/* Add global hwcksum attribute */
19248 	if (hwcksum &&
19249 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19250 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19251 		    "checksum attribute\n"));
19252 
19253 		TCP_STAT(tcps, tcp_mdt_allocfail);
19254 		return (-1);
19255 	}
19256 
19257 	return (0);
19258 }
19259 
19260 /*
19261  * Smaller and private version of pdescinfo_t used specifically for TCP,
19262  * which allows for only two payload spans per packet.
19263  */
19264 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19265 
19266 /*
19267  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19268  * scheme, and returns one the following:
19269  *
19270  * -1 = failed allocation.
19271  *  0 = success; burst count reached, or usable send window is too small,
19272  *      and that we'd rather wait until later before sending again.
19273  */
19274 static int
19275 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19276     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19277     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19278     const int mdt_thres)
19279 {
19280 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19281 	multidata_t	*mmd;
19282 	uint_t		obsegs, obbytes, hdr_frag_sz;
19283 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19284 	int		num_burst_seg, max_pld;
19285 	pdesc_t		*pkt;
19286 	tcp_pdescinfo_t	tcp_pkt_info;
19287 	pdescinfo_t	*pkt_info;
19288 	int		pbuf_idx, pbuf_idx_nxt;
19289 	int		seg_len, len, spill, af;
19290 	boolean_t	add_buffer, zcopy, clusterwide;
19291 	boolean_t	rconfirm = B_FALSE;
19292 	boolean_t	done = B_FALSE;
19293 	uint32_t	cksum;
19294 	uint32_t	hwcksum_flags;
19295 	ire_t		*ire = NULL;
19296 	ill_t		*ill;
19297 	ipha_t		*ipha;
19298 	ip6_t		*ip6h;
19299 	ipaddr_t	src, dst;
19300 	ill_zerocopy_capab_t *zc_cap = NULL;
19301 	uint16_t	*up;
19302 	int		err;
19303 	conn_t		*connp;
19304 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19305 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19306 	int		usable_mmd, tail_unsent_mmd;
19307 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19308 	mblk_t		*xmit_tail_mmd;
19309 	netstackid_t	stack_id;
19310 
19311 #ifdef	_BIG_ENDIAN
19312 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19313 #else
19314 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19315 #endif
19316 
19317 #define	PREP_NEW_MULTIDATA() {			\
19318 	mmd = NULL;				\
19319 	md_mp = md_hbuf = NULL;			\
19320 	cur_hdr_off = 0;			\
19321 	max_pld = tcp->tcp_mdt_max_pld;		\
19322 	pbuf_idx = pbuf_idx_nxt = -1;		\
19323 	add_buffer = B_TRUE;			\
19324 	zcopy = B_FALSE;			\
19325 }
19326 
19327 #define	PREP_NEW_PBUF() {			\
19328 	md_pbuf = md_pbuf_nxt = NULL;		\
19329 	pbuf_idx = pbuf_idx_nxt = -1;		\
19330 	cur_pld_off = 0;			\
19331 	first_snxt = *snxt;			\
19332 	ASSERT(*tail_unsent > 0);		\
19333 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19334 }
19335 
19336 	ASSERT(mdt_thres >= mss);
19337 	ASSERT(*usable > 0 && *usable > mdt_thres);
19338 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19339 	ASSERT(!TCP_IS_DETACHED(tcp));
19340 	ASSERT(tcp->tcp_valid_bits == 0 ||
19341 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19342 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19343 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19344 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19345 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19346 
19347 	connp = tcp->tcp_connp;
19348 	ASSERT(connp != NULL);
19349 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19350 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19351 
19352 	stack_id = connp->conn_netstack->netstack_stackid;
19353 
19354 	usable_mmd = tail_unsent_mmd = 0;
19355 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
19356 	xmit_tail_mmd = NULL;
19357 	/*
19358 	 * Note that tcp will only declare at most 2 payload spans per
19359 	 * packet, which is much lower than the maximum allowable number
19360 	 * of packet spans per Multidata.  For this reason, we use the
19361 	 * privately declared and smaller descriptor info structure, in
19362 	 * order to save some stack space.
19363 	 */
19364 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19365 
19366 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19367 	if (af == AF_INET) {
19368 		dst = tcp->tcp_ipha->ipha_dst;
19369 		src = tcp->tcp_ipha->ipha_src;
19370 		ASSERT(!CLASSD(dst));
19371 	}
19372 	ASSERT(af == AF_INET ||
19373 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19374 
19375 	obsegs = obbytes = 0;
19376 	num_burst_seg = tcp->tcp_snd_burst;
19377 	md_mp_head = NULL;
19378 	PREP_NEW_MULTIDATA();
19379 
19380 	/*
19381 	 * Before we go on further, make sure there is an IRE that we can
19382 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19383 	 * in proceeding any further, and we should just hand everything
19384 	 * off to the legacy path.
19385 	 */
19386 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19387 		goto legacy_send_no_md;
19388 
19389 	ASSERT(ire != NULL);
19390 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19391 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19392 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19393 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19394 	/*
19395 	 * If we do support loopback for MDT (which requires modifications
19396 	 * to the receiving paths), the following assertions should go away,
19397 	 * and we would be sending the Multidata to loopback conn later on.
19398 	 */
19399 	ASSERT(!IRE_IS_LOCAL(ire));
19400 	ASSERT(ire->ire_stq != NULL);
19401 
19402 	ill = ire_to_ill(ire);
19403 	ASSERT(ill != NULL);
19404 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19405 
19406 	if (!tcp->tcp_ire_ill_check_done) {
19407 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19408 		tcp->tcp_ire_ill_check_done = B_TRUE;
19409 	}
19410 
19411 	/*
19412 	 * If the underlying interface conditions have changed, or if the
19413 	 * new interface does not support MDT, go back to legacy path.
19414 	 */
19415 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19416 		/* don't go through this path anymore for this connection */
19417 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19418 		tcp->tcp_mdt = B_FALSE;
19419 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19420 		    "interface %s\n", (void *)connp, ill->ill_name));
19421 		/* IRE will be released prior to returning */
19422 		goto legacy_send_no_md;
19423 	}
19424 
19425 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19426 		zc_cap = ill->ill_zerocopy_capab;
19427 
19428 	/*
19429 	 * Check if we can take tcp fast-path. Note that "incomplete"
19430 	 * ire's (where the link-layer for next hop is not resolved
19431 	 * or where the fast-path header in nce_fp_mp is not available
19432 	 * yet) are sent down the legacy (slow) path.
19433 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19434 	 */
19435 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19436 		/* IRE will be released prior to returning */
19437 		goto legacy_send_no_md;
19438 	}
19439 
19440 	/* go to legacy path if interface doesn't support zerocopy */
19441 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19442 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19443 		/* IRE will be released prior to returning */
19444 		goto legacy_send_no_md;
19445 	}
19446 
19447 	/* does the interface support hardware checksum offload? */
19448 	hwcksum_flags = 0;
19449 	if (ILL_HCKSUM_CAPABLE(ill) &&
19450 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19451 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19452 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19453 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19454 		    HCKSUM_IPHDRCKSUM)
19455 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19456 
19457 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19458 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19459 			hwcksum_flags |= HCK_FULLCKSUM;
19460 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19461 		    HCKSUM_INET_PARTIAL)
19462 			hwcksum_flags |= HCK_PARTIALCKSUM;
19463 	}
19464 
19465 	/*
19466 	 * Each header fragment consists of the leading extra space,
19467 	 * followed by the TCP/IP header, and the trailing extra space.
19468 	 * We make sure that each header fragment begins on a 32-bit
19469 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19470 	 * aligned in tcp_mdt_update).
19471 	 */
19472 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19473 	    tcp->tcp_mdt_hdr_tail), 4);
19474 
19475 	/* are we starting from the beginning of data block? */
19476 	if (*tail_unsent == 0) {
19477 		*xmit_tail = (*xmit_tail)->b_cont;
19478 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19479 		*tail_unsent = (int)MBLKL(*xmit_tail);
19480 	}
19481 
19482 	/*
19483 	 * Here we create one or more Multidata messages, each made up of
19484 	 * one header buffer and up to N payload buffers.  This entire
19485 	 * operation is done within two loops:
19486 	 *
19487 	 * The outer loop mostly deals with creating the Multidata message,
19488 	 * as well as the header buffer that gets added to it.  It also
19489 	 * links the Multidata messages together such that all of them can
19490 	 * be sent down to the lower layer in a single putnext call; this
19491 	 * linking behavior depends on the tcp_mdt_chain tunable.
19492 	 *
19493 	 * The inner loop takes an existing Multidata message, and adds
19494 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19495 	 * packetizes those buffers by filling up the corresponding header
19496 	 * buffer fragments with the proper IP and TCP headers, and by
19497 	 * describing the layout of each packet in the packet descriptors
19498 	 * that get added to the Multidata.
19499 	 */
19500 	do {
19501 		/*
19502 		 * If usable send window is too small, or data blocks in
19503 		 * transmit list are smaller than our threshold (i.e. app
19504 		 * performs large writes followed by small ones), we hand
19505 		 * off the control over to the legacy path.  Note that we'll
19506 		 * get back the control once it encounters a large block.
19507 		 */
19508 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19509 		    (*xmit_tail)->b_cont != NULL &&
19510 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19511 			/* send down what we've got so far */
19512 			if (md_mp_head != NULL) {
19513 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19514 				    obsegs, obbytes, &rconfirm);
19515 			}
19516 			/*
19517 			 * Pass control over to tcp_send(), but tell it to
19518 			 * return to us once a large-size transmission is
19519 			 * possible.
19520 			 */
19521 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19522 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19523 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19524 			    tail_unsent, xmit_tail, local_time,
19525 			    mdt_thres)) <= 0) {
19526 				/* burst count reached, or alloc failed */
19527 				IRE_REFRELE(ire);
19528 				return (err);
19529 			}
19530 
19531 			/* tcp_send() may have sent everything, so check */
19532 			if (*usable <= 0) {
19533 				IRE_REFRELE(ire);
19534 				return (0);
19535 			}
19536 
19537 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19538 			/*
19539 			 * We may have delivered the Multidata, so make sure
19540 			 * to re-initialize before the next round.
19541 			 */
19542 			md_mp_head = NULL;
19543 			obsegs = obbytes = 0;
19544 			num_burst_seg = tcp->tcp_snd_burst;
19545 			PREP_NEW_MULTIDATA();
19546 
19547 			/* are we starting from the beginning of data block? */
19548 			if (*tail_unsent == 0) {
19549 				*xmit_tail = (*xmit_tail)->b_cont;
19550 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19551 				    (uintptr_t)INT_MAX);
19552 				*tail_unsent = (int)MBLKL(*xmit_tail);
19553 			}
19554 		}
19555 		/*
19556 		 * Record current values for parameters we may need to pass
19557 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
19558 		 * each iteration of the outer loop (each multidata message
19559 		 * creation). If we have a failure in the inner loop, we send
19560 		 * any complete multidata messages we have before reverting
19561 		 * to using the traditional non-md path.
19562 		 */
19563 		snxt_mmd = *snxt;
19564 		usable_mmd = *usable;
19565 		xmit_tail_mmd = *xmit_tail;
19566 		tail_unsent_mmd = *tail_unsent;
19567 		obsegs_mmd = obsegs;
19568 		obbytes_mmd = obbytes;
19569 
19570 		/*
19571 		 * max_pld limits the number of mblks in tcp's transmit
19572 		 * queue that can be added to a Multidata message.  Once
19573 		 * this counter reaches zero, no more additional mblks
19574 		 * can be added to it.  What happens afterwards depends
19575 		 * on whether or not we are set to chain the Multidata
19576 		 * messages.  If we are to link them together, reset
19577 		 * max_pld to its original value (tcp_mdt_max_pld) and
19578 		 * prepare to create a new Multidata message which will
19579 		 * get linked to md_mp_head.  Else, leave it alone and
19580 		 * let the inner loop break on its own.
19581 		 */
19582 		if (tcp_mdt_chain && max_pld == 0)
19583 			PREP_NEW_MULTIDATA();
19584 
19585 		/* adding a payload buffer; re-initialize values */
19586 		if (add_buffer)
19587 			PREP_NEW_PBUF();
19588 
19589 		/*
19590 		 * If we don't have a Multidata, either because we just
19591 		 * (re)entered this outer loop, or after we branched off
19592 		 * to tcp_send above, setup the Multidata and header
19593 		 * buffer to be used.
19594 		 */
19595 		if (md_mp == NULL) {
19596 			int md_hbuflen;
19597 			uint32_t start, stuff;
19598 
19599 			/*
19600 			 * Calculate Multidata header buffer size large enough
19601 			 * to hold all of the headers that can possibly be
19602 			 * sent at this moment.  We'd rather over-estimate
19603 			 * the size than running out of space; this is okay
19604 			 * since this buffer is small anyway.
19605 			 */
19606 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19607 
19608 			/*
19609 			 * Start and stuff offset for partial hardware
19610 			 * checksum offload; these are currently for IPv4.
19611 			 * For full checksum offload, they are set to zero.
19612 			 */
19613 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19614 				if (af == AF_INET) {
19615 					start = IP_SIMPLE_HDR_LENGTH;
19616 					stuff = IP_SIMPLE_HDR_LENGTH +
19617 					    TCP_CHECKSUM_OFFSET;
19618 				} else {
19619 					start = IPV6_HDR_LEN;
19620 					stuff = IPV6_HDR_LEN +
19621 					    TCP_CHECKSUM_OFFSET;
19622 				}
19623 			} else {
19624 				start = stuff = 0;
19625 			}
19626 
19627 			/*
19628 			 * Create the header buffer, Multidata, as well as
19629 			 * any necessary attributes (destination address,
19630 			 * SAP and hardware checksum offload) that should
19631 			 * be associated with the Multidata message.
19632 			 */
19633 			ASSERT(cur_hdr_off == 0);
19634 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19635 			    ((md_hbuf->b_wptr += md_hbuflen),
19636 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19637 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19638 			    /* fastpath mblk */
19639 			    ire->ire_nce->nce_res_mp,
19640 			    /* hardware checksum enabled */
19641 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19642 			    /* hardware checksum offsets */
19643 			    start, stuff, 0,
19644 			    /* hardware checksum flag */
19645 			    hwcksum_flags, tcps) != 0)) {
19646 legacy_send:
19647 				/*
19648 				 * We arrive here from a failure within the
19649 				 * inner (packetizer) loop or we fail one of
19650 				 * the conditionals above. We restore the
19651 				 * previously checkpointed values for:
19652 				 *    xmit_tail
19653 				 *    usable
19654 				 *    tail_unsent
19655 				 *    snxt
19656 				 *    obbytes
19657 				 *    obsegs
19658 				 * We should then be able to dispatch any
19659 				 * complete multidata before reverting to the
19660 				 * traditional path with consistent parameters
19661 				 * (the inner loop updates these as it
19662 				 * iterates).
19663 				 */
19664 				*xmit_tail = xmit_tail_mmd;
19665 				*usable = usable_mmd;
19666 				*tail_unsent = tail_unsent_mmd;
19667 				*snxt = snxt_mmd;
19668 				obbytes = obbytes_mmd;
19669 				obsegs = obsegs_mmd;
19670 				if (md_mp != NULL) {
19671 					/* Unlink message from the chain */
19672 					if (md_mp_head != NULL) {
19673 						err = (intptr_t)rmvb(md_mp_head,
19674 						    md_mp);
19675 						/*
19676 						 * We can't assert that rmvb
19677 						 * did not return -1, since we
19678 						 * may get here before linkb
19679 						 * happens.  We do, however,
19680 						 * check if we just removed the
19681 						 * only element in the list.
19682 						 */
19683 						if (err == 0)
19684 							md_mp_head = NULL;
19685 					}
19686 					/* md_hbuf gets freed automatically */
19687 					TCP_STAT(tcps, tcp_mdt_discarded);
19688 					freeb(md_mp);
19689 				} else {
19690 					/* Either allocb or mmd_alloc failed */
19691 					TCP_STAT(tcps, tcp_mdt_allocfail);
19692 					if (md_hbuf != NULL)
19693 						freeb(md_hbuf);
19694 				}
19695 
19696 				/* send down what we've got so far */
19697 				if (md_mp_head != NULL) {
19698 					tcp_multisend_data(tcp, ire, ill,
19699 					    md_mp_head, obsegs, obbytes,
19700 					    &rconfirm);
19701 				}
19702 legacy_send_no_md:
19703 				if (ire != NULL)
19704 					IRE_REFRELE(ire);
19705 				/*
19706 				 * Too bad; let the legacy path handle this.
19707 				 * We specify INT_MAX for the threshold, since
19708 				 * we gave up with the Multidata processings
19709 				 * and let the old path have it all.
19710 				 */
19711 				TCP_STAT(tcps, tcp_mdt_legacy_all);
19712 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19713 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19714 				    snxt, tail_unsent, xmit_tail, local_time,
19715 				    INT_MAX));
19716 			}
19717 
19718 			/* link to any existing ones, if applicable */
19719 			TCP_STAT(tcps, tcp_mdt_allocd);
19720 			if (md_mp_head == NULL) {
19721 				md_mp_head = md_mp;
19722 			} else if (tcp_mdt_chain) {
19723 				TCP_STAT(tcps, tcp_mdt_linked);
19724 				linkb(md_mp_head, md_mp);
19725 			}
19726 		}
19727 
19728 		ASSERT(md_mp_head != NULL);
19729 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19730 		ASSERT(md_mp != NULL && mmd != NULL);
19731 		ASSERT(md_hbuf != NULL);
19732 
19733 		/*
19734 		 * Packetize the transmittable portion of the data block;
19735 		 * each data block is essentially added to the Multidata
19736 		 * as a payload buffer.  We also deal with adding more
19737 		 * than one payload buffers, which happens when the remaining
19738 		 * packetized portion of the current payload buffer is less
19739 		 * than MSS, while the next data block in transmit queue
19740 		 * has enough data to make up for one.  This "spillover"
19741 		 * case essentially creates a split-packet, where portions
19742 		 * of the packet's payload fragments may span across two
19743 		 * virtually discontiguous address blocks.
19744 		 */
19745 		seg_len = mss;
19746 		do {
19747 			len = seg_len;
19748 
19749 			/* one must remain NULL for DTRACE_IP_FASTPATH */
19750 			ipha = NULL;
19751 			ip6h = NULL;
19752 
19753 			ASSERT(len > 0);
19754 			ASSERT(max_pld >= 0);
19755 			ASSERT(!add_buffer || cur_pld_off == 0);
19756 
19757 			/*
19758 			 * First time around for this payload buffer; note
19759 			 * in the case of a spillover, the following has
19760 			 * been done prior to adding the split-packet
19761 			 * descriptor to Multidata, and we don't want to
19762 			 * repeat the process.
19763 			 */
19764 			if (add_buffer) {
19765 				ASSERT(mmd != NULL);
19766 				ASSERT(md_pbuf == NULL);
19767 				ASSERT(md_pbuf_nxt == NULL);
19768 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19769 
19770 				/*
19771 				 * Have we reached the limit?  We'd get to
19772 				 * this case when we're not chaining the
19773 				 * Multidata messages together, and since
19774 				 * we're done, terminate this loop.
19775 				 */
19776 				if (max_pld == 0)
19777 					break; /* done */
19778 
19779 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19780 					TCP_STAT(tcps, tcp_mdt_allocfail);
19781 					goto legacy_send; /* out_of_mem */
19782 				}
19783 
19784 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19785 				    zc_cap != NULL) {
19786 					if (!ip_md_zcopy_attr(mmd, NULL,
19787 					    zc_cap->ill_zerocopy_flags)) {
19788 						freeb(md_pbuf);
19789 						TCP_STAT(tcps,
19790 						    tcp_mdt_allocfail);
19791 						/* out_of_mem */
19792 						goto legacy_send;
19793 					}
19794 					zcopy = B_TRUE;
19795 				}
19796 
19797 				md_pbuf->b_rptr += base_pld_off;
19798 
19799 				/*
19800 				 * Add a payload buffer to the Multidata; this
19801 				 * operation must not fail, or otherwise our
19802 				 * logic in this routine is broken.  There
19803 				 * is no memory allocation done by the
19804 				 * routine, so any returned failure simply
19805 				 * tells us that we've done something wrong.
19806 				 *
19807 				 * A failure tells us that either we're adding
19808 				 * the same payload buffer more than once, or
19809 				 * we're trying to add more buffers than
19810 				 * allowed (max_pld calculation is wrong).
19811 				 * None of the above cases should happen, and
19812 				 * we panic because either there's horrible
19813 				 * heap corruption, and/or programming mistake.
19814 				 */
19815 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19816 				if (pbuf_idx < 0) {
19817 					cmn_err(CE_PANIC, "tcp_multisend: "
19818 					    "payload buffer logic error "
19819 					    "detected for tcp %p mmd %p "
19820 					    "pbuf %p (%d)\n",
19821 					    (void *)tcp, (void *)mmd,
19822 					    (void *)md_pbuf, pbuf_idx);
19823 				}
19824 
19825 				ASSERT(max_pld > 0);
19826 				--max_pld;
19827 				add_buffer = B_FALSE;
19828 			}
19829 
19830 			ASSERT(md_mp_head != NULL);
19831 			ASSERT(md_pbuf != NULL);
19832 			ASSERT(md_pbuf_nxt == NULL);
19833 			ASSERT(pbuf_idx != -1);
19834 			ASSERT(pbuf_idx_nxt == -1);
19835 			ASSERT(*usable > 0);
19836 
19837 			/*
19838 			 * We spillover to the next payload buffer only
19839 			 * if all of the following is true:
19840 			 *
19841 			 *   1. There is not enough data on the current
19842 			 *	payload buffer to make up `len',
19843 			 *   2. We are allowed to send `len',
19844 			 *   3. The next payload buffer length is large
19845 			 *	enough to accomodate `spill'.
19846 			 */
19847 			if ((spill = len - *tail_unsent) > 0 &&
19848 			    *usable >= len &&
19849 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19850 			    max_pld > 0) {
19851 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19852 				if (md_pbuf_nxt == NULL) {
19853 					TCP_STAT(tcps, tcp_mdt_allocfail);
19854 					goto legacy_send; /* out_of_mem */
19855 				}
19856 
19857 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19858 				    zc_cap != NULL) {
19859 					if (!ip_md_zcopy_attr(mmd, NULL,
19860 					    zc_cap->ill_zerocopy_flags)) {
19861 						freeb(md_pbuf_nxt);
19862 						TCP_STAT(tcps,
19863 						    tcp_mdt_allocfail);
19864 						/* out_of_mem */
19865 						goto legacy_send;
19866 					}
19867 					zcopy = B_TRUE;
19868 				}
19869 
19870 				/*
19871 				 * See comments above on the first call to
19872 				 * mmd_addpldbuf for explanation on the panic.
19873 				 */
19874 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19875 				if (pbuf_idx_nxt < 0) {
19876 					panic("tcp_multisend: "
19877 					    "next payload buffer logic error "
19878 					    "detected for tcp %p mmd %p "
19879 					    "pbuf %p (%d)\n",
19880 					    (void *)tcp, (void *)mmd,
19881 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19882 				}
19883 
19884 				ASSERT(max_pld > 0);
19885 				--max_pld;
19886 			} else if (spill > 0) {
19887 				/*
19888 				 * If there's a spillover, but the following
19889 				 * xmit_tail couldn't give us enough octets
19890 				 * to reach "len", then stop the current
19891 				 * Multidata creation and let the legacy
19892 				 * tcp_send() path take over.  We don't want
19893 				 * to send the tiny segment as part of this
19894 				 * Multidata for performance reasons; instead,
19895 				 * we let the legacy path deal with grouping
19896 				 * it with the subsequent small mblks.
19897 				 */
19898 				if (*usable >= len &&
19899 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19900 					max_pld = 0;
19901 					break;	/* done */
19902 				}
19903 
19904 				/*
19905 				 * We can't spillover, and we are near
19906 				 * the end of the current payload buffer,
19907 				 * so send what's left.
19908 				 */
19909 				ASSERT(*tail_unsent > 0);
19910 				len = *tail_unsent;
19911 			}
19912 
19913 			/* tail_unsent is negated if there is a spillover */
19914 			*tail_unsent -= len;
19915 			*usable -= len;
19916 			ASSERT(*usable >= 0);
19917 
19918 			if (*usable < mss)
19919 				seg_len = *usable;
19920 			/*
19921 			 * Sender SWS avoidance; see comments in tcp_send();
19922 			 * everything else is the same, except that we only
19923 			 * do this here if there is no more data to be sent
19924 			 * following the current xmit_tail.  We don't check
19925 			 * for 1-byte urgent data because we shouldn't get
19926 			 * here if TCP_URG_VALID is set.
19927 			 */
19928 			if (*usable > 0 && *usable < mss &&
19929 			    ((md_pbuf_nxt == NULL &&
19930 			    (*xmit_tail)->b_cont == NULL) ||
19931 			    (md_pbuf_nxt != NULL &&
19932 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19933 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19934 			    (tcp->tcp_unsent -
19935 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19936 			    !tcp->tcp_zero_win_probe) {
19937 				if ((*snxt + len) == tcp->tcp_snxt &&
19938 				    (*snxt + len) == tcp->tcp_suna) {
19939 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19940 				}
19941 				done = B_TRUE;
19942 			}
19943 
19944 			/*
19945 			 * Prime pump for IP's checksumming on our behalf;
19946 			 * include the adjustment for a source route if any.
19947 			 * Do this only for software/partial hardware checksum
19948 			 * offload, as this field gets zeroed out later for
19949 			 * the full hardware checksum offload case.
19950 			 */
19951 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19952 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19953 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19954 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19955 			}
19956 
19957 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19958 			*snxt += len;
19959 
19960 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19961 			/*
19962 			 * We set the PUSH bit only if TCP has no more buffered
19963 			 * data to be transmitted (or if sender SWS avoidance
19964 			 * takes place), as opposed to setting it for every
19965 			 * last packet in the burst.
19966 			 */
19967 			if (done ||
19968 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19969 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19970 
19971 			/*
19972 			 * Set FIN bit if this is our last segment; snxt
19973 			 * already includes its length, and it will not
19974 			 * be adjusted after this point.
19975 			 */
19976 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19977 			    *snxt == tcp->tcp_fss) {
19978 				if (!tcp->tcp_fin_acked) {
19979 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19980 					BUMP_MIB(&tcps->tcps_mib,
19981 					    tcpOutControl);
19982 				}
19983 				if (!tcp->tcp_fin_sent) {
19984 					tcp->tcp_fin_sent = B_TRUE;
19985 					/*
19986 					 * tcp state must be ESTABLISHED
19987 					 * in order for us to get here in
19988 					 * the first place.
19989 					 */
19990 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19991 
19992 					/*
19993 					 * Upon returning from this routine,
19994 					 * tcp_wput_data() will set tcp_snxt
19995 					 * to be equal to snxt + tcp_fin_sent.
19996 					 * This is essentially the same as
19997 					 * setting it to tcp_fss + 1.
19998 					 */
19999 				}
20000 			}
20001 
20002 			tcp->tcp_last_sent_len = (ushort_t)len;
20003 
20004 			len += tcp_hdr_len;
20005 			if (tcp->tcp_ipversion == IPV4_VERSION)
20006 				tcp->tcp_ipha->ipha_length = htons(len);
20007 			else
20008 				tcp->tcp_ip6h->ip6_plen = htons(len -
20009 				    ((char *)&tcp->tcp_ip6h[1] -
20010 				    tcp->tcp_iphc));
20011 
20012 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20013 
20014 			/* setup header fragment */
20015 			PDESC_HDR_ADD(pkt_info,
20016 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20017 			    tcp->tcp_mdt_hdr_head,		/* head room */
20018 			    tcp_hdr_len,			/* len */
20019 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20020 
20021 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20022 			    hdr_frag_sz);
20023 			ASSERT(MBLKIN(md_hbuf,
20024 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20025 			    PDESC_HDRSIZE(pkt_info)));
20026 
20027 			/* setup first payload fragment */
20028 			PDESC_PLD_INIT(pkt_info);
20029 			PDESC_PLD_SPAN_ADD(pkt_info,
20030 			    pbuf_idx,				/* index */
20031 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20032 			    tcp->tcp_last_sent_len);		/* len */
20033 
20034 			/* create a split-packet in case of a spillover */
20035 			if (md_pbuf_nxt != NULL) {
20036 				ASSERT(spill > 0);
20037 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20038 				ASSERT(!add_buffer);
20039 
20040 				md_pbuf = md_pbuf_nxt;
20041 				md_pbuf_nxt = NULL;
20042 				pbuf_idx = pbuf_idx_nxt;
20043 				pbuf_idx_nxt = -1;
20044 				cur_pld_off = spill;
20045 
20046 				/* trim out first payload fragment */
20047 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20048 
20049 				/* setup second payload fragment */
20050 				PDESC_PLD_SPAN_ADD(pkt_info,
20051 				    pbuf_idx,			/* index */
20052 				    md_pbuf->b_rptr,		/* start */
20053 				    spill);			/* len */
20054 
20055 				if ((*xmit_tail)->b_next == NULL) {
20056 					/*
20057 					 * Store the lbolt used for RTT
20058 					 * estimation. We can only record one
20059 					 * timestamp per mblk so we do it when
20060 					 * we reach the end of the payload
20061 					 * buffer.  Also we only take a new
20062 					 * timestamp sample when the previous
20063 					 * timed data from the same mblk has
20064 					 * been ack'ed.
20065 					 */
20066 					(*xmit_tail)->b_prev = local_time;
20067 					(*xmit_tail)->b_next =
20068 					    (mblk_t *)(uintptr_t)first_snxt;
20069 				}
20070 
20071 				first_snxt = *snxt - spill;
20072 
20073 				/*
20074 				 * Advance xmit_tail; usable could be 0 by
20075 				 * the time we got here, but we made sure
20076 				 * above that we would only spillover to
20077 				 * the next data block if usable includes
20078 				 * the spilled-over amount prior to the
20079 				 * subtraction.  Therefore, we are sure
20080 				 * that xmit_tail->b_cont can't be NULL.
20081 				 */
20082 				ASSERT((*xmit_tail)->b_cont != NULL);
20083 				*xmit_tail = (*xmit_tail)->b_cont;
20084 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20085 				    (uintptr_t)INT_MAX);
20086 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20087 			} else {
20088 				cur_pld_off += tcp->tcp_last_sent_len;
20089 			}
20090 
20091 			/*
20092 			 * Fill in the header using the template header, and
20093 			 * add options such as time-stamp, ECN and/or SACK,
20094 			 * as needed.
20095 			 */
20096 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20097 			    (clock_t)local_time, num_sack_blk);
20098 
20099 			/* take care of some IP header businesses */
20100 			if (af == AF_INET) {
20101 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20102 
20103 				ASSERT(OK_32PTR((uchar_t *)ipha));
20104 				ASSERT(PDESC_HDRL(pkt_info) >=
20105 				    IP_SIMPLE_HDR_LENGTH);
20106 				ASSERT(ipha->ipha_version_and_hdr_length ==
20107 				    IP_SIMPLE_HDR_VERSION);
20108 
20109 				/*
20110 				 * Assign ident value for current packet; see
20111 				 * related comments in ip_wput_ire() about the
20112 				 * contract private interface with clustering
20113 				 * group.
20114 				 */
20115 				clusterwide = B_FALSE;
20116 				if (cl_inet_ipident != NULL) {
20117 					ASSERT(cl_inet_isclusterwide != NULL);
20118 					if ((*cl_inet_isclusterwide)(stack_id,
20119 					    IPPROTO_IP, AF_INET,
20120 					    (uint8_t *)(uintptr_t)src, NULL)) {
20121 						ipha->ipha_ident =
20122 						    (*cl_inet_ipident)(stack_id,
20123 						    IPPROTO_IP, AF_INET,
20124 						    (uint8_t *)(uintptr_t)src,
20125 						    (uint8_t *)(uintptr_t)dst,
20126 						    NULL);
20127 						clusterwide = B_TRUE;
20128 					}
20129 				}
20130 
20131 				if (!clusterwide) {
20132 					ipha->ipha_ident = (uint16_t)
20133 					    atomic_add_32_nv(
20134 						&ire->ire_ident, 1);
20135 				}
20136 #ifndef _BIG_ENDIAN
20137 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20138 				    (ipha->ipha_ident >> 8);
20139 #endif
20140 			} else {
20141 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20142 
20143 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20144 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20145 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20146 				ASSERT(PDESC_HDRL(pkt_info) >=
20147 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20148 				    TCP_CHECKSUM_SIZE));
20149 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20150 
20151 				if (tcp->tcp_ip_forward_progress) {
20152 					rconfirm = B_TRUE;
20153 					tcp->tcp_ip_forward_progress = B_FALSE;
20154 				}
20155 			}
20156 
20157 			/* at least one payload span, and at most two */
20158 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20159 
20160 			/* add the packet descriptor to Multidata */
20161 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20162 			    KM_NOSLEEP)) == NULL) {
20163 				/*
20164 				 * Any failure other than ENOMEM indicates
20165 				 * that we have passed in invalid pkt_info
20166 				 * or parameters to mmd_addpdesc, which must
20167 				 * not happen.
20168 				 *
20169 				 * EINVAL is a result of failure on boundary
20170 				 * checks against the pkt_info contents.  It
20171 				 * should not happen, and we panic because
20172 				 * either there's horrible heap corruption,
20173 				 * and/or programming mistake.
20174 				 */
20175 				if (err != ENOMEM) {
20176 					cmn_err(CE_PANIC, "tcp_multisend: "
20177 					    "pdesc logic error detected for "
20178 					    "tcp %p mmd %p pinfo %p (%d)\n",
20179 					    (void *)tcp, (void *)mmd,
20180 					    (void *)pkt_info, err);
20181 				}
20182 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20183 				goto legacy_send; /* out_of_mem */
20184 			}
20185 			ASSERT(pkt != NULL);
20186 
20187 			/* calculate IP header and TCP checksums */
20188 			if (af == AF_INET) {
20189 				/* calculate pseudo-header checksum */
20190 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20191 				    (src >> 16) + (src & 0xFFFF);
20192 
20193 				/* offset for TCP header checksum */
20194 				up = IPH_TCPH_CHECKSUMP(ipha,
20195 				    IP_SIMPLE_HDR_LENGTH);
20196 			} else {
20197 				up = (uint16_t *)&ip6h->ip6_src;
20198 
20199 				/* calculate pseudo-header checksum */
20200 				cksum = up[0] + up[1] + up[2] + up[3] +
20201 				    up[4] + up[5] + up[6] + up[7] +
20202 				    up[8] + up[9] + up[10] + up[11] +
20203 				    up[12] + up[13] + up[14] + up[15];
20204 
20205 				/* Fold the initial sum */
20206 				cksum = (cksum & 0xffff) + (cksum >> 16);
20207 
20208 				up = (uint16_t *)(((uchar_t *)ip6h) +
20209 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20210 			}
20211 
20212 			if (hwcksum_flags & HCK_FULLCKSUM) {
20213 				/* clear checksum field for hardware */
20214 				*up = 0;
20215 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20216 				uint32_t sum;
20217 
20218 				/* pseudo-header checksumming */
20219 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20220 				sum = (sum & 0xFFFF) + (sum >> 16);
20221 				*up = (sum & 0xFFFF) + (sum >> 16);
20222 			} else {
20223 				/* software checksumming */
20224 				TCP_STAT(tcps, tcp_out_sw_cksum);
20225 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20226 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20227 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20228 				    cksum + IP_TCP_CSUM_COMP);
20229 				if (*up == 0)
20230 					*up = 0xFFFF;
20231 			}
20232 
20233 			/* IPv4 header checksum */
20234 			if (af == AF_INET) {
20235 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20236 					ipha->ipha_hdr_checksum = 0;
20237 				} else {
20238 					IP_HDR_CKSUM(ipha, cksum,
20239 					    ((uint32_t *)ipha)[0],
20240 					    ((uint16_t *)ipha)[4]);
20241 				}
20242 			}
20243 
20244 			if (af == AF_INET &&
20245 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20246 			    af == AF_INET6 &&
20247 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20248 				mblk_t	*mp, *mp1;
20249 				uchar_t	*hdr_rptr, *hdr_wptr;
20250 				uchar_t	*pld_rptr, *pld_wptr;
20251 
20252 				/*
20253 				 * We reconstruct a pseudo packet for the hooks
20254 				 * framework using mmd_transform_link().
20255 				 * If it is a split packet we pullup the
20256 				 * payload. FW_HOOKS expects a pkt comprising
20257 				 * of two mblks: a header and the payload.
20258 				 */
20259 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20260 					TCP_STAT(tcps, tcp_mdt_allocfail);
20261 					goto legacy_send;
20262 				}
20263 
20264 				if (pkt_info->pld_cnt > 1) {
20265 					/* split payload, more than one pld */
20266 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20267 					    NULL) {
20268 						freemsg(mp);
20269 						TCP_STAT(tcps,
20270 						    tcp_mdt_allocfail);
20271 						goto legacy_send;
20272 					}
20273 					freemsg(mp->b_cont);
20274 					mp->b_cont = mp1;
20275 				} else {
20276 					mp1 = mp->b_cont;
20277 				}
20278 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20279 
20280 				/*
20281 				 * Remember the message offsets. This is so we
20282 				 * can detect changes when we return from the
20283 				 * FW_HOOKS callbacks.
20284 				 */
20285 				hdr_rptr = mp->b_rptr;
20286 				hdr_wptr = mp->b_wptr;
20287 				pld_rptr = mp->b_cont->b_rptr;
20288 				pld_wptr = mp->b_cont->b_wptr;
20289 
20290 				if (af == AF_INET) {
20291 					DTRACE_PROBE4(
20292 					    ip4__physical__out__start,
20293 					    ill_t *, NULL,
20294 					    ill_t *, ill,
20295 					    ipha_t *, ipha,
20296 					    mblk_t *, mp);
20297 					FW_HOOKS(
20298 					    ipst->ips_ip4_physical_out_event,
20299 					    ipst->ips_ipv4firewall_physical_out,
20300 					    NULL, ill, ipha, mp, mp, 0, ipst);
20301 					DTRACE_PROBE1(
20302 					    ip4__physical__out__end,
20303 					    mblk_t *, mp);
20304 				} else {
20305 					DTRACE_PROBE4(
20306 					    ip6__physical__out_start,
20307 					    ill_t *, NULL,
20308 					    ill_t *, ill,
20309 					    ip6_t *, ip6h,
20310 					    mblk_t *, mp);
20311 					FW_HOOKS6(
20312 					    ipst->ips_ip6_physical_out_event,
20313 					    ipst->ips_ipv6firewall_physical_out,
20314 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20315 					DTRACE_PROBE1(
20316 					    ip6__physical__out__end,
20317 					    mblk_t *, mp);
20318 				}
20319 
20320 				if (mp == NULL ||
20321 				    (mp1 = mp->b_cont) == NULL ||
20322 				    mp->b_rptr != hdr_rptr ||
20323 				    mp->b_wptr != hdr_wptr ||
20324 				    mp1->b_rptr != pld_rptr ||
20325 				    mp1->b_wptr != pld_wptr ||
20326 				    mp1->b_cont != NULL) {
20327 					/*
20328 					 * We abandon multidata processing and
20329 					 * return to the normal path, either
20330 					 * when a packet is blocked, or when
20331 					 * the boundaries of header buffer or
20332 					 * payload buffer have been changed by
20333 					 * FW_HOOKS[6].
20334 					 */
20335 					if (mp != NULL)
20336 						freemsg(mp);
20337 					goto legacy_send;
20338 				}
20339 				/* Finished with the pseudo packet */
20340 				freemsg(mp);
20341 			}
20342 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
20343 			    ill, ipha, ip6h);
20344 			/* advance header offset */
20345 			cur_hdr_off += hdr_frag_sz;
20346 
20347 			obbytes += tcp->tcp_last_sent_len;
20348 			++obsegs;
20349 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20350 		    *tail_unsent > 0);
20351 
20352 		if ((*xmit_tail)->b_next == NULL) {
20353 			/*
20354 			 * Store the lbolt used for RTT estimation. We can only
20355 			 * record one timestamp per mblk so we do it when we
20356 			 * reach the end of the payload buffer. Also we only
20357 			 * take a new timestamp sample when the previous timed
20358 			 * data from the same mblk has been ack'ed.
20359 			 */
20360 			(*xmit_tail)->b_prev = local_time;
20361 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20362 		}
20363 
20364 		ASSERT(*tail_unsent >= 0);
20365 		if (*tail_unsent > 0) {
20366 			/*
20367 			 * We got here because we broke out of the above
20368 			 * loop due to of one of the following cases:
20369 			 *
20370 			 *   1. len < adjusted MSS (i.e. small),
20371 			 *   2. Sender SWS avoidance,
20372 			 *   3. max_pld is zero.
20373 			 *
20374 			 * We are done for this Multidata, so trim our
20375 			 * last payload buffer (if any) accordingly.
20376 			 */
20377 			if (md_pbuf != NULL)
20378 				md_pbuf->b_wptr -= *tail_unsent;
20379 		} else if (*usable > 0) {
20380 			*xmit_tail = (*xmit_tail)->b_cont;
20381 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20382 			    (uintptr_t)INT_MAX);
20383 			*tail_unsent = (int)MBLKL(*xmit_tail);
20384 			add_buffer = B_TRUE;
20385 		}
20386 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20387 	    (tcp_mdt_chain || max_pld > 0));
20388 
20389 	if (md_mp_head != NULL) {
20390 		/* send everything down */
20391 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20392 		    &rconfirm);
20393 	}
20394 
20395 #undef PREP_NEW_MULTIDATA
20396 #undef PREP_NEW_PBUF
20397 #undef IPVER
20398 
20399 	IRE_REFRELE(ire);
20400 	return (0);
20401 }
20402 
20403 /*
20404  * A wrapper function for sending one or more Multidata messages down to
20405  * the module below ip; this routine does not release the reference of the
20406  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20407  */
20408 static void
20409 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20410     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20411 {
20412 	uint64_t delta;
20413 	nce_t *nce;
20414 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20415 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20416 
20417 	ASSERT(ire != NULL && ill != NULL);
20418 	ASSERT(ire->ire_stq != NULL);
20419 	ASSERT(md_mp_head != NULL);
20420 	ASSERT(rconfirm != NULL);
20421 
20422 	/* adjust MIBs and IRE timestamp */
20423 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
20424 	tcp->tcp_obsegs += obsegs;
20425 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20426 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20427 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20428 
20429 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20430 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20431 	} else {
20432 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20433 	}
20434 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20435 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20436 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20437 
20438 	ire->ire_ob_pkt_count += obsegs;
20439 	if (ire->ire_ipif != NULL)
20440 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20441 	ire->ire_last_used_time = lbolt;
20442 
20443 	if (ipst->ips_ipobs_enabled) {
20444 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
20445 		pdesc_t *dl_pkt;
20446 		pdescinfo_t pinfo;
20447 		mblk_t *nmp;
20448 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
20449 
20450 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
20451 		    (dl_pkt != NULL);
20452 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
20453 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
20454 				continue;
20455 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
20456 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
20457 			freemsg(nmp);
20458 		}
20459 	}
20460 
20461 	/* send it down */
20462 	putnext(ire->ire_stq, md_mp_head);
20463 
20464 	/* we're done for TCP/IPv4 */
20465 	if (tcp->tcp_ipversion == IPV4_VERSION)
20466 		return;
20467 
20468 	nce = ire->ire_nce;
20469 
20470 	ASSERT(nce != NULL);
20471 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20472 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20473 
20474 	/* reachability confirmation? */
20475 	if (*rconfirm) {
20476 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20477 		if (nce->nce_state != ND_REACHABLE) {
20478 			mutex_enter(&nce->nce_lock);
20479 			nce->nce_state = ND_REACHABLE;
20480 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20481 			mutex_exit(&nce->nce_lock);
20482 			(void) untimeout(nce->nce_timeout_id);
20483 			if (ip_debug > 2) {
20484 				/* ip1dbg */
20485 				pr_addr_dbg("tcp_multisend_data: state "
20486 				    "for %s changed to REACHABLE\n",
20487 				    AF_INET6, &ire->ire_addr_v6);
20488 			}
20489 		}
20490 		/* reset transport reachability confirmation */
20491 		*rconfirm = B_FALSE;
20492 	}
20493 
20494 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20495 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20496 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20497 
20498 	if (delta > (uint64_t)ill->ill_reachable_time) {
20499 		mutex_enter(&nce->nce_lock);
20500 		switch (nce->nce_state) {
20501 		case ND_REACHABLE:
20502 		case ND_STALE:
20503 			/*
20504 			 * ND_REACHABLE is identical to ND_STALE in this
20505 			 * specific case. If reachable time has expired for
20506 			 * this neighbor (delta is greater than reachable
20507 			 * time), conceptually, the neighbor cache is no
20508 			 * longer in REACHABLE state, but already in STALE
20509 			 * state.  So the correct transition here is to
20510 			 * ND_DELAY.
20511 			 */
20512 			nce->nce_state = ND_DELAY;
20513 			mutex_exit(&nce->nce_lock);
20514 			NDP_RESTART_TIMER(nce,
20515 			    ipst->ips_delay_first_probe_time);
20516 			if (ip_debug > 3) {
20517 				/* ip2dbg */
20518 				pr_addr_dbg("tcp_multisend_data: state "
20519 				    "for %s changed to DELAY\n",
20520 				    AF_INET6, &ire->ire_addr_v6);
20521 			}
20522 			break;
20523 		case ND_DELAY:
20524 		case ND_PROBE:
20525 			mutex_exit(&nce->nce_lock);
20526 			/* Timers have already started */
20527 			break;
20528 		case ND_UNREACHABLE:
20529 			/*
20530 			 * ndp timer has detected that this nce is
20531 			 * unreachable and initiated deleting this nce
20532 			 * and all its associated IREs. This is a race
20533 			 * where we found the ire before it was deleted
20534 			 * and have just sent out a packet using this
20535 			 * unreachable nce.
20536 			 */
20537 			mutex_exit(&nce->nce_lock);
20538 			break;
20539 		default:
20540 			ASSERT(0);
20541 		}
20542 	}
20543 }
20544 
20545 /*
20546  * Derived from tcp_send_data().
20547  */
20548 static void
20549 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20550     int num_lso_seg)
20551 {
20552 	ipha_t		*ipha;
20553 	mblk_t		*ire_fp_mp;
20554 	uint_t		ire_fp_mp_len;
20555 	uint32_t	hcksum_txflags = 0;
20556 	ipaddr_t	src;
20557 	ipaddr_t	dst;
20558 	uint32_t	cksum;
20559 	uint16_t	*up;
20560 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20561 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20562 
20563 	ASSERT(DB_TYPE(mp) == M_DATA);
20564 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20565 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20566 	ASSERT(tcp->tcp_connp != NULL);
20567 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20568 
20569 	ipha = (ipha_t *)mp->b_rptr;
20570 	src = ipha->ipha_src;
20571 	dst = ipha->ipha_dst;
20572 
20573 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
20574 
20575 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20576 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20577 	    num_lso_seg);
20578 #ifndef _BIG_ENDIAN
20579 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20580 #endif
20581 	if (tcp->tcp_snd_zcopy_aware) {
20582 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20583 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20584 			mp = tcp_zcopy_disable(tcp, mp);
20585 	}
20586 
20587 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20588 		ASSERT(ill->ill_hcksum_capab != NULL);
20589 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20590 	}
20591 
20592 	/*
20593 	 * Since the TCP checksum should be recalculated by h/w, we can just
20594 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20595 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20596 	 * The partial pseudo-header excludes TCP length, that was calculated
20597 	 * in tcp_send(), so to zero *up before further processing.
20598 	 */
20599 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20600 
20601 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20602 	*up = 0;
20603 
20604 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20605 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20606 
20607 	/*
20608 	 * Append LSO flags and mss to the mp.
20609 	 */
20610 	lso_info_set(mp, mss, HW_LSO);
20611 
20612 	ipha->ipha_fragment_offset_and_flags |=
20613 	    (uint32_t)htons(ire->ire_frag_flag);
20614 
20615 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20616 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20617 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20618 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20619 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20620 
20621 	UPDATE_OB_PKT_COUNT(ire);
20622 	ire->ire_last_used_time = lbolt;
20623 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20624 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20625 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20626 	    ntohs(ipha->ipha_length));
20627 
20628 	DTRACE_PROBE4(ip4__physical__out__start,
20629 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
20630 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
20631 	    ipst->ips_ipv4firewall_physical_out, NULL,
20632 	    ill, ipha, mp, mp, 0, ipst);
20633 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20634 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
20635 
20636 	if (mp != NULL) {
20637 		if (ipst->ips_ipobs_enabled) {
20638 			zoneid_t szone;
20639 
20640 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
20641 			    ipst, ALL_ZONES);
20642 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
20643 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
20644 		}
20645 
20646 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
20647 	}
20648 }
20649 
20650 /*
20651  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20652  * scheme, and returns one of the following:
20653  *
20654  * -1 = failed allocation.
20655  *  0 = success; burst count reached, or usable send window is too small,
20656  *      and that we'd rather wait until later before sending again.
20657  *  1 = success; we are called from tcp_multisend(), and both usable send
20658  *      window and tail_unsent are greater than the MDT threshold, and thus
20659  *      Multidata Transmit should be used instead.
20660  */
20661 static int
20662 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20663     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20664     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20665     const int mdt_thres)
20666 {
20667 	int num_burst_seg = tcp->tcp_snd_burst;
20668 	ire_t		*ire = NULL;
20669 	ill_t		*ill = NULL;
20670 	mblk_t		*ire_fp_mp = NULL;
20671 	uint_t		ire_fp_mp_len = 0;
20672 	int		num_lso_seg = 1;
20673 	uint_t		lso_usable;
20674 	boolean_t	do_lso_send = B_FALSE;
20675 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20676 
20677 	/*
20678 	 * Check LSO capability before any further work. And the similar check
20679 	 * need to be done in for(;;) loop.
20680 	 * LSO will be deployed when therer is more than one mss of available
20681 	 * data and a burst transmission is allowed.
20682 	 */
20683 	if (tcp->tcp_lso &&
20684 	    (tcp->tcp_valid_bits == 0 ||
20685 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20686 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20687 		/*
20688 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20689 		 * Double check LSO usability before going further, since the
20690 		 * underlying interface could have been changed. In case of any
20691 		 * change of LSO capability, set tcp_ire_ill_check_done to
20692 		 * B_FALSE to force to check the ILL with the next send.
20693 		 */
20694 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
20695 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
20696 			/*
20697 			 * Enable LSO with this transmission.
20698 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
20699 			 * IRE_REFRELE(ire) should be called before return.
20700 			 */
20701 			do_lso_send = B_TRUE;
20702 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
20703 			ire_fp_mp_len = MBLKL(ire_fp_mp);
20704 			/* Round up to multiple of 4 */
20705 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
20706 		} else {
20707 			tcp->tcp_lso = B_FALSE;
20708 			tcp->tcp_ire_ill_check_done = B_FALSE;
20709 			do_lso_send = B_FALSE;
20710 			ill = NULL;
20711 		}
20712 	}
20713 
20714 	for (;;) {
20715 		struct datab	*db;
20716 		tcph_t		*tcph;
20717 		uint32_t	sum;
20718 		mblk_t		*mp, *mp1;
20719 		uchar_t		*rptr;
20720 		int		len;
20721 
20722 		/*
20723 		 * If we're called by tcp_multisend(), and the amount of
20724 		 * sendable data as well as the size of current xmit_tail
20725 		 * is beyond the MDT threshold, return to the caller and
20726 		 * let the large data transmit be done using MDT.
20727 		 */
20728 		if (*usable > 0 && *usable > mdt_thres &&
20729 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20730 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20731 			ASSERT(tcp->tcp_mdt);
20732 			return (1);	/* success; do large send */
20733 		}
20734 
20735 		if (num_burst_seg == 0)
20736 			break;		/* success; burst count reached */
20737 
20738 		/*
20739 		 * Calculate the maximum payload length we can send in *one*
20740 		 * time.
20741 		 */
20742 		if (do_lso_send) {
20743 			/*
20744 			 * Check whether need to do LSO any more.
20745 			 */
20746 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20747 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
20748 				lso_usable = MIN(lso_usable,
20749 				    num_burst_seg * mss);
20750 
20751 				num_lso_seg = lso_usable / mss;
20752 				if (lso_usable % mss) {
20753 					num_lso_seg++;
20754 					tcp->tcp_last_sent_len = (ushort_t)
20755 					    (lso_usable % mss);
20756 				} else {
20757 					tcp->tcp_last_sent_len = (ushort_t)mss;
20758 				}
20759 			} else {
20760 				do_lso_send = B_FALSE;
20761 				num_lso_seg = 1;
20762 				lso_usable = mss;
20763 			}
20764 		}
20765 
20766 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
20767 
20768 		/*
20769 		 * Adjust num_burst_seg here.
20770 		 */
20771 		num_burst_seg -= num_lso_seg;
20772 
20773 		len = mss;
20774 		if (len > *usable) {
20775 			ASSERT(do_lso_send == B_FALSE);
20776 
20777 			len = *usable;
20778 			if (len <= 0) {
20779 				/* Terminate the loop */
20780 				break;	/* success; too small */
20781 			}
20782 			/*
20783 			 * Sender silly-window avoidance.
20784 			 * Ignore this if we are going to send a
20785 			 * zero window probe out.
20786 			 *
20787 			 * TODO: force data into microscopic window?
20788 			 *	==> (!pushed || (unsent > usable))
20789 			 */
20790 			if (len < (tcp->tcp_max_swnd >> 1) &&
20791 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20792 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20793 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20794 				/*
20795 				 * If the retransmit timer is not running
20796 				 * we start it so that we will retransmit
20797 				 * in the case when the the receiver has
20798 				 * decremented the window.
20799 				 */
20800 				if (*snxt == tcp->tcp_snxt &&
20801 				    *snxt == tcp->tcp_suna) {
20802 					/*
20803 					 * We are not supposed to send
20804 					 * anything.  So let's wait a little
20805 					 * bit longer before breaking SWS
20806 					 * avoidance.
20807 					 *
20808 					 * What should the value be?
20809 					 * Suggestion: MAX(init rexmit time,
20810 					 * tcp->tcp_rto)
20811 					 */
20812 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20813 				}
20814 				break;	/* success; too small */
20815 			}
20816 		}
20817 
20818 		tcph = tcp->tcp_tcph;
20819 
20820 		/*
20821 		 * The reason to adjust len here is that we need to set flags
20822 		 * and calculate checksum.
20823 		 */
20824 		if (do_lso_send)
20825 			len = lso_usable;
20826 
20827 		*usable -= len; /* Approximate - can be adjusted later */
20828 		if (*usable > 0)
20829 			tcph->th_flags[0] = TH_ACK;
20830 		else
20831 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20832 
20833 		/*
20834 		 * Prime pump for IP's checksumming on our behalf
20835 		 * Include the adjustment for a source route if any.
20836 		 */
20837 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20838 		sum = (sum >> 16) + (sum & 0xFFFF);
20839 		U16_TO_ABE16(sum, tcph->th_sum);
20840 
20841 		U32_TO_ABE32(*snxt, tcph->th_seq);
20842 
20843 		/*
20844 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20845 		 * set.  For the case when TCP_FSS_VALID is the only valid
20846 		 * bit (normal active close), branch off only when we think
20847 		 * that the FIN flag needs to be set.  Note for this case,
20848 		 * that (snxt + len) may not reflect the actual seg_len,
20849 		 * as len may be further reduced in tcp_xmit_mp().  If len
20850 		 * gets modified, we will end up here again.
20851 		 */
20852 		if (tcp->tcp_valid_bits != 0 &&
20853 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20854 		    ((*snxt + len) == tcp->tcp_fss))) {
20855 			uchar_t		*prev_rptr;
20856 			uint32_t	prev_snxt = tcp->tcp_snxt;
20857 
20858 			if (*tail_unsent == 0) {
20859 				ASSERT((*xmit_tail)->b_cont != NULL);
20860 				*xmit_tail = (*xmit_tail)->b_cont;
20861 				prev_rptr = (*xmit_tail)->b_rptr;
20862 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20863 				    (*xmit_tail)->b_rptr);
20864 			} else {
20865 				prev_rptr = (*xmit_tail)->b_rptr;
20866 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20867 				    *tail_unsent;
20868 			}
20869 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20870 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20871 			/* Restore tcp_snxt so we get amount sent right. */
20872 			tcp->tcp_snxt = prev_snxt;
20873 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20874 				/*
20875 				 * If the previous timestamp is still in use,
20876 				 * don't stomp on it.
20877 				 */
20878 				if ((*xmit_tail)->b_next == NULL) {
20879 					(*xmit_tail)->b_prev = local_time;
20880 					(*xmit_tail)->b_next =
20881 					    (mblk_t *)(uintptr_t)(*snxt);
20882 				}
20883 			} else
20884 				(*xmit_tail)->b_rptr = prev_rptr;
20885 
20886 			if (mp == NULL) {
20887 				if (ire != NULL)
20888 					IRE_REFRELE(ire);
20889 				return (-1);
20890 			}
20891 			mp1 = mp->b_cont;
20892 
20893 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
20894 				tcp->tcp_last_sent_len = (ushort_t)len;
20895 			while (mp1->b_cont) {
20896 				*xmit_tail = (*xmit_tail)->b_cont;
20897 				(*xmit_tail)->b_prev = local_time;
20898 				(*xmit_tail)->b_next =
20899 				    (mblk_t *)(uintptr_t)(*snxt);
20900 				mp1 = mp1->b_cont;
20901 			}
20902 			*snxt += len;
20903 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20904 			BUMP_LOCAL(tcp->tcp_obsegs);
20905 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20906 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20907 			tcp_send_data(tcp, q, mp);
20908 			continue;
20909 		}
20910 
20911 		*snxt += len;	/* Adjust later if we don't send all of len */
20912 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20913 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20914 
20915 		if (*tail_unsent) {
20916 			/* Are the bytes above us in flight? */
20917 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20918 			if (rptr != (*xmit_tail)->b_rptr) {
20919 				*tail_unsent -= len;
20920 				if (len <= mss) /* LSO is unusable */
20921 					tcp->tcp_last_sent_len = (ushort_t)len;
20922 				len += tcp_hdr_len;
20923 				if (tcp->tcp_ipversion == IPV4_VERSION)
20924 					tcp->tcp_ipha->ipha_length = htons(len);
20925 				else
20926 					tcp->tcp_ip6h->ip6_plen =
20927 					    htons(len -
20928 					    ((char *)&tcp->tcp_ip6h[1] -
20929 					    tcp->tcp_iphc));
20930 				mp = dupb(*xmit_tail);
20931 				if (mp == NULL) {
20932 					if (ire != NULL)
20933 						IRE_REFRELE(ire);
20934 					return (-1);	/* out_of_mem */
20935 				}
20936 				mp->b_rptr = rptr;
20937 				/*
20938 				 * If the old timestamp is no longer in use,
20939 				 * sample a new timestamp now.
20940 				 */
20941 				if ((*xmit_tail)->b_next == NULL) {
20942 					(*xmit_tail)->b_prev = local_time;
20943 					(*xmit_tail)->b_next =
20944 					    (mblk_t *)(uintptr_t)(*snxt-len);
20945 				}
20946 				goto must_alloc;
20947 			}
20948 		} else {
20949 			*xmit_tail = (*xmit_tail)->b_cont;
20950 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20951 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20952 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20953 			    (*xmit_tail)->b_rptr);
20954 		}
20955 
20956 		(*xmit_tail)->b_prev = local_time;
20957 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20958 
20959 		*tail_unsent -= len;
20960 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
20961 			tcp->tcp_last_sent_len = (ushort_t)len;
20962 
20963 		len += tcp_hdr_len;
20964 		if (tcp->tcp_ipversion == IPV4_VERSION)
20965 			tcp->tcp_ipha->ipha_length = htons(len);
20966 		else
20967 			tcp->tcp_ip6h->ip6_plen = htons(len -
20968 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20969 
20970 		mp = dupb(*xmit_tail);
20971 		if (mp == NULL) {
20972 			if (ire != NULL)
20973 				IRE_REFRELE(ire);
20974 			return (-1);	/* out_of_mem */
20975 		}
20976 
20977 		len = tcp_hdr_len;
20978 		/*
20979 		 * There are four reasons to allocate a new hdr mblk:
20980 		 *  1) The bytes above us are in use by another packet
20981 		 *  2) We don't have good alignment
20982 		 *  3) The mblk is being shared
20983 		 *  4) We don't have enough room for a header
20984 		 */
20985 		rptr = mp->b_rptr - len;
20986 		if (!OK_32PTR(rptr) ||
20987 		    ((db = mp->b_datap), db->db_ref != 2) ||
20988 		    rptr < db->db_base + ire_fp_mp_len) {
20989 			/* NOTE: we assume allocb returns an OK_32PTR */
20990 
20991 		must_alloc:;
20992 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20993 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
20994 			if (mp1 == NULL) {
20995 				freemsg(mp);
20996 				if (ire != NULL)
20997 					IRE_REFRELE(ire);
20998 				return (-1);	/* out_of_mem */
20999 			}
21000 			mp1->b_cont = mp;
21001 			mp = mp1;
21002 			/* Leave room for Link Level header */
21003 			len = tcp_hdr_len;
21004 			rptr =
21005 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21006 			mp->b_wptr = &rptr[len];
21007 		}
21008 
21009 		/*
21010 		 * Fill in the header using the template header, and add
21011 		 * options such as time-stamp, ECN and/or SACK, as needed.
21012 		 */
21013 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21014 
21015 		mp->b_rptr = rptr;
21016 
21017 		if (*tail_unsent) {
21018 			int spill = *tail_unsent;
21019 
21020 			mp1 = mp->b_cont;
21021 			if (mp1 == NULL)
21022 				mp1 = mp;
21023 
21024 			/*
21025 			 * If we're a little short, tack on more mblks until
21026 			 * there is no more spillover.
21027 			 */
21028 			while (spill < 0) {
21029 				mblk_t *nmp;
21030 				int nmpsz;
21031 
21032 				nmp = (*xmit_tail)->b_cont;
21033 				nmpsz = MBLKL(nmp);
21034 
21035 				/*
21036 				 * Excess data in mblk; can we split it?
21037 				 * If MDT is enabled for the connection,
21038 				 * keep on splitting as this is a transient
21039 				 * send path.
21040 				 */
21041 				if (!do_lso_send && !tcp->tcp_mdt &&
21042 				    (spill + nmpsz > 0)) {
21043 					/*
21044 					 * Don't split if stream head was
21045 					 * told to break up larger writes
21046 					 * into smaller ones.
21047 					 */
21048 					if (tcp->tcp_maxpsz > 0)
21049 						break;
21050 
21051 					/*
21052 					 * Next mblk is less than SMSS/2
21053 					 * rounded up to nearest 64-byte;
21054 					 * let it get sent as part of the
21055 					 * next segment.
21056 					 */
21057 					if (tcp->tcp_localnet &&
21058 					    !tcp->tcp_cork &&
21059 					    (nmpsz < roundup((mss >> 1), 64)))
21060 						break;
21061 				}
21062 
21063 				*xmit_tail = nmp;
21064 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21065 				/* Stash for rtt use later */
21066 				(*xmit_tail)->b_prev = local_time;
21067 				(*xmit_tail)->b_next =
21068 				    (mblk_t *)(uintptr_t)(*snxt - len);
21069 				mp1->b_cont = dupb(*xmit_tail);
21070 				mp1 = mp1->b_cont;
21071 
21072 				spill += nmpsz;
21073 				if (mp1 == NULL) {
21074 					*tail_unsent = spill;
21075 					freemsg(mp);
21076 					if (ire != NULL)
21077 						IRE_REFRELE(ire);
21078 					return (-1);	/* out_of_mem */
21079 				}
21080 			}
21081 
21082 			/* Trim back any surplus on the last mblk */
21083 			if (spill >= 0) {
21084 				mp1->b_wptr -= spill;
21085 				*tail_unsent = spill;
21086 			} else {
21087 				/*
21088 				 * We did not send everything we could in
21089 				 * order to remain within the b_cont limit.
21090 				 */
21091 				*usable -= spill;
21092 				*snxt += spill;
21093 				tcp->tcp_last_sent_len += spill;
21094 				UPDATE_MIB(&tcps->tcps_mib,
21095 				    tcpOutDataBytes, spill);
21096 				/*
21097 				 * Adjust the checksum
21098 				 */
21099 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21100 				sum += spill;
21101 				sum = (sum >> 16) + (sum & 0xFFFF);
21102 				U16_TO_ABE16(sum, tcph->th_sum);
21103 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21104 					sum = ntohs(
21105 					    ((ipha_t *)rptr)->ipha_length) +
21106 					    spill;
21107 					((ipha_t *)rptr)->ipha_length =
21108 					    htons(sum);
21109 				} else {
21110 					sum = ntohs(
21111 					    ((ip6_t *)rptr)->ip6_plen) +
21112 					    spill;
21113 					((ip6_t *)rptr)->ip6_plen =
21114 					    htons(sum);
21115 				}
21116 				*tail_unsent = 0;
21117 			}
21118 		}
21119 		if (tcp->tcp_ip_forward_progress) {
21120 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21121 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21122 			tcp->tcp_ip_forward_progress = B_FALSE;
21123 		}
21124 
21125 		if (do_lso_send) {
21126 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21127 			    num_lso_seg);
21128 			tcp->tcp_obsegs += num_lso_seg;
21129 
21130 			TCP_STAT(tcps, tcp_lso_times);
21131 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21132 		} else {
21133 			tcp_send_data(tcp, q, mp);
21134 			BUMP_LOCAL(tcp->tcp_obsegs);
21135 		}
21136 	}
21137 
21138 	if (ire != NULL)
21139 		IRE_REFRELE(ire);
21140 	return (0);
21141 }
21142 
21143 /* Unlink and return any mblk that looks like it contains a MDT info */
21144 static mblk_t *
21145 tcp_mdt_info_mp(mblk_t *mp)
21146 {
21147 	mblk_t	*prev_mp;
21148 
21149 	for (;;) {
21150 		prev_mp = mp;
21151 		/* no more to process? */
21152 		if ((mp = mp->b_cont) == NULL)
21153 			break;
21154 
21155 		switch (DB_TYPE(mp)) {
21156 		case M_CTL:
21157 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21158 				continue;
21159 			ASSERT(prev_mp != NULL);
21160 			prev_mp->b_cont = mp->b_cont;
21161 			mp->b_cont = NULL;
21162 			return (mp);
21163 		default:
21164 			break;
21165 		}
21166 	}
21167 	return (mp);
21168 }
21169 
21170 /* MDT info update routine, called when IP notifies us about MDT */
21171 static void
21172 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21173 {
21174 	boolean_t prev_state;
21175 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21176 
21177 	/*
21178 	 * IP is telling us to abort MDT on this connection?  We know
21179 	 * this because the capability is only turned off when IP
21180 	 * encounters some pathological cases, e.g. link-layer change
21181 	 * where the new driver doesn't support MDT, or in situation
21182 	 * where MDT usage on the link-layer has been switched off.
21183 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21184 	 * if the link-layer doesn't support MDT, and if it does, it
21185 	 * will indicate that the feature is to be turned on.
21186 	 */
21187 	prev_state = tcp->tcp_mdt;
21188 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21189 	if (!tcp->tcp_mdt && !first) {
21190 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21191 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21192 		    (void *)tcp->tcp_connp));
21193 	}
21194 
21195 	/*
21196 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21197 	 * so disable MDT otherwise.  The checks are done here
21198 	 * and in tcp_wput_data().
21199 	 */
21200 	if (tcp->tcp_mdt &&
21201 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21202 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21203 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21204 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21205 		tcp->tcp_mdt = B_FALSE;
21206 
21207 	if (tcp->tcp_mdt) {
21208 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21209 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21210 			    "version (%d), expected version is %d",
21211 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21212 			tcp->tcp_mdt = B_FALSE;
21213 			return;
21214 		}
21215 
21216 		/*
21217 		 * We need the driver to be able to handle at least three
21218 		 * spans per packet in order for tcp MDT to be utilized.
21219 		 * The first is for the header portion, while the rest are
21220 		 * needed to handle a packet that straddles across two
21221 		 * virtually non-contiguous buffers; a typical tcp packet
21222 		 * therefore consists of only two spans.  Note that we take
21223 		 * a zero as "don't care".
21224 		 */
21225 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21226 		    mdt_capab->ill_mdt_span_limit < 3) {
21227 			tcp->tcp_mdt = B_FALSE;
21228 			return;
21229 		}
21230 
21231 		/* a zero means driver wants default value */
21232 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21233 		    tcps->tcps_mdt_max_pbufs);
21234 		if (tcp->tcp_mdt_max_pld == 0)
21235 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21236 
21237 		/* ensure 32-bit alignment */
21238 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21239 		    mdt_capab->ill_mdt_hdr_head), 4);
21240 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21241 		    mdt_capab->ill_mdt_hdr_tail), 4);
21242 
21243 		if (!first && !prev_state) {
21244 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21245 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21246 			    (void *)tcp->tcp_connp));
21247 		}
21248 	}
21249 }
21250 
21251 /* Unlink and return any mblk that looks like it contains a LSO info */
21252 static mblk_t *
21253 tcp_lso_info_mp(mblk_t *mp)
21254 {
21255 	mblk_t	*prev_mp;
21256 
21257 	for (;;) {
21258 		prev_mp = mp;
21259 		/* no more to process? */
21260 		if ((mp = mp->b_cont) == NULL)
21261 			break;
21262 
21263 		switch (DB_TYPE(mp)) {
21264 		case M_CTL:
21265 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21266 				continue;
21267 			ASSERT(prev_mp != NULL);
21268 			prev_mp->b_cont = mp->b_cont;
21269 			mp->b_cont = NULL;
21270 			return (mp);
21271 		default:
21272 			break;
21273 		}
21274 	}
21275 
21276 	return (mp);
21277 }
21278 
21279 /* LSO info update routine, called when IP notifies us about LSO */
21280 static void
21281 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21282 {
21283 	tcp_stack_t *tcps = tcp->tcp_tcps;
21284 
21285 	/*
21286 	 * IP is telling us to abort LSO on this connection?  We know
21287 	 * this because the capability is only turned off when IP
21288 	 * encounters some pathological cases, e.g. link-layer change
21289 	 * where the new NIC/driver doesn't support LSO, or in situation
21290 	 * where LSO usage on the link-layer has been switched off.
21291 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21292 	 * if the link-layer doesn't support LSO, and if it does, it
21293 	 * will indicate that the feature is to be turned on.
21294 	 */
21295 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21296 	TCP_STAT(tcps, tcp_lso_enabled);
21297 
21298 	/*
21299 	 * We currently only support LSO on simple TCP/IPv4,
21300 	 * so disable LSO otherwise.  The checks are done here
21301 	 * and in tcp_wput_data().
21302 	 */
21303 	if (tcp->tcp_lso &&
21304 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21305 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21306 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21307 		tcp->tcp_lso = B_FALSE;
21308 		TCP_STAT(tcps, tcp_lso_disabled);
21309 	} else {
21310 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21311 		    lso_capab->ill_lso_max);
21312 	}
21313 }
21314 
21315 static void
21316 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21317 {
21318 	conn_t *connp = tcp->tcp_connp;
21319 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21320 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21321 
21322 	ASSERT(ire != NULL);
21323 
21324 	/*
21325 	 * We may be in the fastpath here, and although we essentially do
21326 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21327 	 * we try to keep things as brief as possible.  After all, these
21328 	 * are only best-effort checks, and we do more thorough ones prior
21329 	 * to calling tcp_send()/tcp_multisend().
21330 	 */
21331 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21332 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21333 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21334 	    !(ire->ire_flags & RTF_MULTIRT) &&
21335 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21336 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21337 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21338 			/* Cache the result */
21339 			connp->conn_lso_ok = B_TRUE;
21340 
21341 			ASSERT(ill->ill_lso_capab != NULL);
21342 			if (!ill->ill_lso_capab->ill_lso_on) {
21343 				ill->ill_lso_capab->ill_lso_on = 1;
21344 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21345 				    "LSO for interface %s\n", (void *)connp,
21346 				    ill->ill_name));
21347 			}
21348 			tcp_lso_update(tcp, ill->ill_lso_capab);
21349 		} else if (ipst->ips_ip_multidata_outbound &&
21350 		    ILL_MDT_CAPABLE(ill)) {
21351 			/* Cache the result */
21352 			connp->conn_mdt_ok = B_TRUE;
21353 
21354 			ASSERT(ill->ill_mdt_capab != NULL);
21355 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21356 				ill->ill_mdt_capab->ill_mdt_on = 1;
21357 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21358 				    "MDT for interface %s\n", (void *)connp,
21359 				    ill->ill_name));
21360 			}
21361 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21362 		}
21363 	}
21364 
21365 	/*
21366 	 * The goal is to reduce the number of generated tcp segments by
21367 	 * setting the maxpsz multiplier to 0; this will have an affect on
21368 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21369 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21370 	 * of outbound segments and incoming ACKs, thus allowing for better
21371 	 * network and system performance.  In contrast the legacy behavior
21372 	 * may result in sending less than SMSS size, because the last mblk
21373 	 * for some packets may have more data than needed to make up SMSS,
21374 	 * and the legacy code refused to "split" it.
21375 	 *
21376 	 * We apply the new behavior on following situations:
21377 	 *
21378 	 *   1) Loopback connections,
21379 	 *   2) Connections in which the remote peer is not on local subnet,
21380 	 *   3) Local subnet connections over the bge interface (see below).
21381 	 *
21382 	 * Ideally, we would like this behavior to apply for interfaces other
21383 	 * than bge.  However, doing so would negatively impact drivers which
21384 	 * perform dynamic mapping and unmapping of DMA resources, which are
21385 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21386 	 * packet will be generated by tcp).  The bge driver does not suffer
21387 	 * from this, as it copies the mblks into pre-mapped buffers, and
21388 	 * therefore does not require more I/O resources than before.
21389 	 *
21390 	 * Otherwise, this behavior is present on all network interfaces when
21391 	 * the destination endpoint is non-local, since reducing the number
21392 	 * of packets in general is good for the network.
21393 	 *
21394 	 * TODO We need to remove this hard-coded conditional for bge once
21395 	 *	a better "self-tuning" mechanism, or a way to comprehend
21396 	 *	the driver transmit strategy is devised.  Until the solution
21397 	 *	is found and well understood, we live with this hack.
21398 	 */
21399 	if (!tcp_static_maxpsz &&
21400 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21401 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21402 		/* override the default value */
21403 		tcp->tcp_maxpsz = 0;
21404 
21405 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21406 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21407 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21408 	}
21409 
21410 	/* set the stream head parameters accordingly */
21411 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21412 }
21413 
21414 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21415 static void
21416 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21417 {
21418 	uchar_t	fval = *mp->b_rptr;
21419 	mblk_t	*tail;
21420 	queue_t	*q = tcp->tcp_wq;
21421 
21422 	/* TODO: How should flush interact with urgent data? */
21423 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21424 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21425 		/*
21426 		 * Flush only data that has not yet been put on the wire.  If
21427 		 * we flush data that we have already transmitted, life, as we
21428 		 * know it, may come to an end.
21429 		 */
21430 		tail = tcp->tcp_xmit_tail;
21431 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21432 		tcp->tcp_xmit_tail_unsent = 0;
21433 		tcp->tcp_unsent = 0;
21434 		if (tail->b_wptr != tail->b_rptr)
21435 			tail = tail->b_cont;
21436 		if (tail) {
21437 			mblk_t **excess = &tcp->tcp_xmit_head;
21438 			for (;;) {
21439 				mblk_t *mp1 = *excess;
21440 				if (mp1 == tail)
21441 					break;
21442 				tcp->tcp_xmit_tail = mp1;
21443 				tcp->tcp_xmit_last = mp1;
21444 				excess = &mp1->b_cont;
21445 			}
21446 			*excess = NULL;
21447 			tcp_close_mpp(&tail);
21448 			if (tcp->tcp_snd_zcopy_aware)
21449 				tcp_zcopy_notify(tcp);
21450 		}
21451 		/*
21452 		 * We have no unsent data, so unsent must be less than
21453 		 * tcp_xmit_lowater, so re-enable flow.
21454 		 */
21455 		mutex_enter(&tcp->tcp_non_sq_lock);
21456 		if (tcp->tcp_flow_stopped) {
21457 			tcp_clrqfull(tcp);
21458 		}
21459 		mutex_exit(&tcp->tcp_non_sq_lock);
21460 	}
21461 	/*
21462 	 * TODO: you can't just flush these, you have to increase rwnd for one
21463 	 * thing.  For another, how should urgent data interact?
21464 	 */
21465 	if (fval & FLUSHR) {
21466 		*mp->b_rptr = fval & ~FLUSHW;
21467 		/* XXX */
21468 		qreply(q, mp);
21469 		return;
21470 	}
21471 	freemsg(mp);
21472 }
21473 
21474 /*
21475  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21476  * messages.
21477  */
21478 static void
21479 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21480 {
21481 	mblk_t	*mp1;
21482 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
21483 	STRUCT_HANDLE(strbuf, sb);
21484 	queue_t *q = tcp->tcp_wq;
21485 	int	error;
21486 	uint_t	addrlen;
21487 
21488 	/* Make sure it is one of ours. */
21489 	switch (iocp->ioc_cmd) {
21490 	case TI_GETMYNAME:
21491 	case TI_GETPEERNAME:
21492 		break;
21493 	default:
21494 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21495 		return;
21496 	}
21497 	switch (mi_copy_state(q, mp, &mp1)) {
21498 	case -1:
21499 		return;
21500 	case MI_COPY_CASE(MI_COPY_IN, 1):
21501 		break;
21502 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21503 		/* Copy out the strbuf. */
21504 		mi_copyout(q, mp);
21505 		return;
21506 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21507 		/* All done. */
21508 		mi_copy_done(q, mp, 0);
21509 		return;
21510 	default:
21511 		mi_copy_done(q, mp, EPROTO);
21512 		return;
21513 	}
21514 	/* Check alignment of the strbuf */
21515 	if (!OK_32PTR(mp1->b_rptr)) {
21516 		mi_copy_done(q, mp, EINVAL);
21517 		return;
21518 	}
21519 
21520 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
21521 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21522 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21523 		mi_copy_done(q, mp, EINVAL);
21524 		return;
21525 	}
21526 
21527 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21528 	if (mp1 == NULL)
21529 		return;
21530 
21531 	switch (iocp->ioc_cmd) {
21532 	case TI_GETMYNAME:
21533 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
21534 		break;
21535 	case TI_GETPEERNAME:
21536 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
21537 		break;
21538 	}
21539 
21540 	if (error != 0) {
21541 		mi_copy_done(q, mp, error);
21542 	} else {
21543 		mp1->b_wptr += addrlen;
21544 		STRUCT_FSET(sb, len, addrlen);
21545 
21546 		/* Copy out the address */
21547 		mi_copyout(q, mp);
21548 	}
21549 }
21550 
21551 static void
21552 tcp_use_pure_tpi(tcp_t *tcp)
21553 {
21554 #ifdef	_ILP32
21555 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
21556 #else
21557 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21558 #endif
21559 	/*
21560 	 * Insert this socket into the acceptor hash.
21561 	 * We might need it for T_CONN_RES message
21562 	 */
21563 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21564 
21565 	tcp->tcp_issocket = B_FALSE;
21566 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
21567 }
21568 
21569 /*
21570  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21571  * messages.
21572  */
21573 /* ARGSUSED */
21574 static void
21575 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21576 {
21577 	conn_t 	*connp = (conn_t *)arg;
21578 	tcp_t	*tcp = connp->conn_tcp;
21579 	queue_t	*q = tcp->tcp_wq;
21580 	struct iocblk	*iocp;
21581 
21582 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21583 	/*
21584 	 * Try and ASSERT the minimum possible references on the
21585 	 * conn early enough. Since we are executing on write side,
21586 	 * the connection is obviously not detached and that means
21587 	 * there is a ref each for TCP and IP. Since we are behind
21588 	 * the squeue, the minimum references needed are 3. If the
21589 	 * conn is in classifier hash list, there should be an
21590 	 * extra ref for that (we check both the possibilities).
21591 	 */
21592 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21593 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21594 
21595 	iocp = (struct iocblk *)mp->b_rptr;
21596 	switch (iocp->ioc_cmd) {
21597 	case TCP_IOC_DEFAULT_Q:
21598 		/* Wants to be the default wq. */
21599 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21600 			iocp->ioc_error = EPERM;
21601 			iocp->ioc_count = 0;
21602 			mp->b_datap->db_type = M_IOCACK;
21603 			qreply(q, mp);
21604 			return;
21605 		}
21606 		tcp_def_q_set(tcp, mp);
21607 		return;
21608 	case _SIOCSOCKFALLBACK:
21609 		/*
21610 		 * Either sockmod is about to be popped and the socket
21611 		 * would now be treated as a plain stream, or a module
21612 		 * is about to be pushed so we could no longer use read-
21613 		 * side synchronous streams for fused loopback tcp.
21614 		 * Drain any queued data and disable direct sockfs
21615 		 * interface from now on.
21616 		 */
21617 		if (!tcp->tcp_issocket) {
21618 			DB_TYPE(mp) = M_IOCNAK;
21619 			iocp->ioc_error = EINVAL;
21620 		} else {
21621 			tcp_use_pure_tpi(tcp);
21622 			DB_TYPE(mp) = M_IOCACK;
21623 			iocp->ioc_error = 0;
21624 		}
21625 		iocp->ioc_count = 0;
21626 		iocp->ioc_rval = 0;
21627 		qreply(q, mp);
21628 		return;
21629 	}
21630 	CALL_IP_WPUT(connp, q, mp);
21631 }
21632 
21633 /*
21634  * This routine is called by tcp_wput() to handle all TPI requests.
21635  */
21636 /* ARGSUSED */
21637 static void
21638 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21639 {
21640 	conn_t 	*connp = (conn_t *)arg;
21641 	tcp_t	*tcp = connp->conn_tcp;
21642 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21643 	uchar_t *rptr;
21644 	t_scalar_t type;
21645 	cred_t *cr;
21646 
21647 	/*
21648 	 * Try and ASSERT the minimum possible references on the
21649 	 * conn early enough. Since we are executing on write side,
21650 	 * the connection is obviously not detached and that means
21651 	 * there is a ref each for TCP and IP. Since we are behind
21652 	 * the squeue, the minimum references needed are 3. If the
21653 	 * conn is in classifier hash list, there should be an
21654 	 * extra ref for that (we check both the possibilities).
21655 	 */
21656 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21657 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21658 
21659 	rptr = mp->b_rptr;
21660 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21661 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21662 		type = ((union T_primitives *)rptr)->type;
21663 		if (type == T_EXDATA_REQ) {
21664 			tcp_output_urgent(connp, mp, arg2);
21665 		} else if (type != T_DATA_REQ) {
21666 			goto non_urgent_data;
21667 		} else {
21668 			/* TODO: options, flags, ... from user */
21669 			/* Set length to zero for reclamation below */
21670 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21671 			freeb(mp);
21672 		}
21673 		return;
21674 	} else {
21675 		if (tcp->tcp_debug) {
21676 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21677 			    "tcp_wput_proto, dropping one...");
21678 		}
21679 		freemsg(mp);
21680 		return;
21681 	}
21682 
21683 non_urgent_data:
21684 
21685 	switch ((int)tprim->type) {
21686 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21687 		/*
21688 		 * save the kssl_ent_t from the next block, and convert this
21689 		 * back to a normal bind_req.
21690 		 */
21691 		if (mp->b_cont != NULL) {
21692 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21693 
21694 			if (tcp->tcp_kssl_ent != NULL) {
21695 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21696 				    KSSL_NO_PROXY);
21697 				tcp->tcp_kssl_ent = NULL;
21698 			}
21699 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21700 			    sizeof (kssl_ent_t));
21701 			kssl_hold_ent(tcp->tcp_kssl_ent);
21702 			freemsg(mp->b_cont);
21703 			mp->b_cont = NULL;
21704 		}
21705 		tprim->type = T_BIND_REQ;
21706 
21707 	/* FALLTHROUGH */
21708 	case O_T_BIND_REQ:	/* bind request */
21709 	case T_BIND_REQ:	/* new semantics bind request */
21710 		tcp_tpi_bind(tcp, mp);
21711 		break;
21712 	case T_UNBIND_REQ:	/* unbind request */
21713 		tcp_tpi_unbind(tcp, mp);
21714 		break;
21715 	case O_T_CONN_RES:	/* old connection response XXX */
21716 	case T_CONN_RES:	/* connection response */
21717 		tcp_tli_accept(tcp, mp);
21718 		break;
21719 	case T_CONN_REQ:	/* connection request */
21720 		tcp_tpi_connect(tcp, mp);
21721 		break;
21722 	case T_DISCON_REQ:	/* disconnect request */
21723 		tcp_disconnect(tcp, mp);
21724 		break;
21725 	case T_CAPABILITY_REQ:
21726 		tcp_capability_req(tcp, mp);	/* capability request */
21727 		break;
21728 	case T_INFO_REQ:	/* information request */
21729 		tcp_info_req(tcp, mp);
21730 		break;
21731 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21732 	case T_OPTMGMT_REQ:
21733 		/*
21734 		 * Note:  no support for snmpcom_req() through new
21735 		 * T_OPTMGMT_REQ. See comments in ip.c
21736 		 */
21737 
21738 		/*
21739 		 * All Solaris components should pass a db_credp
21740 		 * for this TPI message, hence we ASSERT.
21741 		 * But in case there is some other M_PROTO that looks
21742 		 * like a TPI message sent by some other kernel
21743 		 * component, we check and return an error.
21744 		 */
21745 		cr = msg_getcred(mp, NULL);
21746 		ASSERT(cr != NULL);
21747 		if (cr == NULL) {
21748 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
21749 			return;
21750 		}
21751 		/*
21752 		 * If EINPROGRESS is returned, the request has been queued
21753 		 * for subsequent processing by ip_restart_optmgmt(), which
21754 		 * will do the CONN_DEC_REF().
21755 		 */
21756 		CONN_INC_REF(connp);
21757 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
21758 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21759 			    B_TRUE) != EINPROGRESS) {
21760 				CONN_DEC_REF(connp);
21761 			}
21762 		} else {
21763 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21764 			    B_TRUE) != EINPROGRESS) {
21765 				CONN_DEC_REF(connp);
21766 			}
21767 		}
21768 		break;
21769 
21770 	case T_UNITDATA_REQ:	/* unitdata request */
21771 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21772 		break;
21773 	case T_ORDREL_REQ:	/* orderly release req */
21774 		freemsg(mp);
21775 
21776 		if (tcp->tcp_fused)
21777 			tcp_unfuse(tcp);
21778 
21779 		if (tcp_xmit_end(tcp) != 0) {
21780 			/*
21781 			 * We were crossing FINs and got a reset from
21782 			 * the other side. Just ignore it.
21783 			 */
21784 			if (tcp->tcp_debug) {
21785 				(void) strlog(TCP_MOD_ID, 0, 1,
21786 				    SL_ERROR|SL_TRACE,
21787 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21788 				    "state %s",
21789 				    tcp_display(tcp, NULL,
21790 				    DISP_ADDR_AND_PORT));
21791 			}
21792 		}
21793 		break;
21794 	case T_ADDR_REQ:
21795 		tcp_addr_req(tcp, mp);
21796 		break;
21797 	default:
21798 		if (tcp->tcp_debug) {
21799 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21800 			    "tcp_wput_proto, bogus TPI msg, type %d",
21801 			    tprim->type);
21802 		}
21803 		/*
21804 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21805 		 * to recover.
21806 		 */
21807 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21808 		break;
21809 	}
21810 }
21811 
21812 /*
21813  * The TCP write service routine should never be called...
21814  */
21815 /* ARGSUSED */
21816 static void
21817 tcp_wsrv(queue_t *q)
21818 {
21819 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
21820 
21821 	TCP_STAT(tcps, tcp_wsrv_called);
21822 }
21823 
21824 /* Non overlapping byte exchanger */
21825 static void
21826 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21827 {
21828 	uchar_t	uch;
21829 
21830 	while (len-- > 0) {
21831 		uch = a[len];
21832 		a[len] = b[len];
21833 		b[len] = uch;
21834 	}
21835 }
21836 
21837 /*
21838  * Send out a control packet on the tcp connection specified.  This routine
21839  * is typically called where we need a simple ACK or RST generated.
21840  */
21841 static void
21842 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21843 {
21844 	uchar_t		*rptr;
21845 	tcph_t		*tcph;
21846 	ipha_t		*ipha = NULL;
21847 	ip6_t		*ip6h = NULL;
21848 	uint32_t	sum;
21849 	int		tcp_hdr_len;
21850 	int		tcp_ip_hdr_len;
21851 	mblk_t		*mp;
21852 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21853 
21854 	/*
21855 	 * Save sum for use in source route later.
21856 	 */
21857 	ASSERT(tcp != NULL);
21858 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21859 	tcp_hdr_len = tcp->tcp_hdr_len;
21860 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21861 
21862 	/* If a text string is passed in with the request, pass it to strlog. */
21863 	if (str != NULL && tcp->tcp_debug) {
21864 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21865 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21866 		    str, seq, ack, ctl);
21867 	}
21868 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
21869 	    BPRI_MED);
21870 	if (mp == NULL) {
21871 		return;
21872 	}
21873 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
21874 	mp->b_rptr = rptr;
21875 	mp->b_wptr = &rptr[tcp_hdr_len];
21876 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21877 
21878 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21879 		ipha = (ipha_t *)rptr;
21880 		ipha->ipha_length = htons(tcp_hdr_len);
21881 	} else {
21882 		ip6h = (ip6_t *)rptr;
21883 		ASSERT(tcp != NULL);
21884 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21885 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21886 	}
21887 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21888 	tcph->th_flags[0] = (uint8_t)ctl;
21889 	if (ctl & TH_RST) {
21890 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
21891 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
21892 		/*
21893 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21894 		 */
21895 		if (tcp->tcp_snd_ts_ok &&
21896 		    tcp->tcp_state > TCPS_SYN_SENT) {
21897 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21898 			*(mp->b_wptr) = TCPOPT_EOL;
21899 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21900 				ipha->ipha_length = htons(tcp_hdr_len -
21901 				    TCPOPT_REAL_TS_LEN);
21902 			} else {
21903 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21904 				    TCPOPT_REAL_TS_LEN);
21905 			}
21906 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21907 			sum -= TCPOPT_REAL_TS_LEN;
21908 		}
21909 	}
21910 	if (ctl & TH_ACK) {
21911 		if (tcp->tcp_snd_ts_ok) {
21912 			U32_TO_BE32(lbolt,
21913 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21914 			U32_TO_BE32(tcp->tcp_ts_recent,
21915 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21916 		}
21917 
21918 		/* Update the latest receive window size in TCP header. */
21919 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21920 		    tcph->th_win);
21921 		tcp->tcp_rack = ack;
21922 		tcp->tcp_rack_cnt = 0;
21923 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
21924 	}
21925 	BUMP_LOCAL(tcp->tcp_obsegs);
21926 	U32_TO_BE32(seq, tcph->th_seq);
21927 	U32_TO_BE32(ack, tcph->th_ack);
21928 	/*
21929 	 * Include the adjustment for a source route if any.
21930 	 */
21931 	sum = (sum >> 16) + (sum & 0xFFFF);
21932 	U16_TO_BE16(sum, tcph->th_sum);
21933 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21934 }
21935 
21936 /*
21937  * If this routine returns B_TRUE, TCP can generate a RST in response
21938  * to a segment.  If it returns B_FALSE, TCP should not respond.
21939  */
21940 static boolean_t
21941 tcp_send_rst_chk(tcp_stack_t *tcps)
21942 {
21943 	clock_t	now;
21944 
21945 	/*
21946 	 * TCP needs to protect itself from generating too many RSTs.
21947 	 * This can be a DoS attack by sending us random segments
21948 	 * soliciting RSTs.
21949 	 *
21950 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21951 	 * in each 1 second interval.  In this way, TCP still generate
21952 	 * RSTs in normal cases but when under attack, the impact is
21953 	 * limited.
21954 	 */
21955 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
21956 		now = lbolt;
21957 		/* lbolt can wrap around. */
21958 		if ((tcps->tcps_last_rst_intrvl > now) ||
21959 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
21960 		    1*SECONDS)) {
21961 			tcps->tcps_last_rst_intrvl = now;
21962 			tcps->tcps_rst_cnt = 1;
21963 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
21964 			return (B_FALSE);
21965 		}
21966 	}
21967 	return (B_TRUE);
21968 }
21969 
21970 /*
21971  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21972  */
21973 static void
21974 tcp_ip_ire_mark_advice(tcp_t *tcp)
21975 {
21976 	mblk_t *mp;
21977 	ipic_t *ipic;
21978 
21979 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21980 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21981 		    &ipic);
21982 	} else {
21983 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21984 		    &ipic);
21985 	}
21986 	if (mp == NULL)
21987 		return;
21988 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21989 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21990 }
21991 
21992 /*
21993  * Return an IP advice ioctl mblk and set ipic to be the pointer
21994  * to the advice structure.
21995  */
21996 static mblk_t *
21997 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21998 {
21999 	struct iocblk *ioc;
22000 	mblk_t *mp, *mp1;
22001 
22002 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22003 	if (mp == NULL)
22004 		return (NULL);
22005 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22006 	*ipic = (ipic_t *)mp->b_rptr;
22007 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22008 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22009 
22010 	bcopy(addr, *ipic + 1, addr_len);
22011 
22012 	(*ipic)->ipic_addr_length = addr_len;
22013 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22014 
22015 	mp1 = mkiocb(IP_IOCTL);
22016 	if (mp1 == NULL) {
22017 		freemsg(mp);
22018 		return (NULL);
22019 	}
22020 	mp1->b_cont = mp;
22021 	ioc = (struct iocblk *)mp1->b_rptr;
22022 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22023 
22024 	return (mp1);
22025 }
22026 
22027 /*
22028  * Generate a reset based on an inbound packet, connp is set by caller
22029  * when RST is in response to an unexpected inbound packet for which
22030  * there is active tcp state in the system.
22031  *
22032  * IPSEC NOTE : Try to send the reply with the same protection as it came
22033  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22034  * the packet will go out at the same level of protection as it came in by
22035  * converting the IPSEC_IN to IPSEC_OUT.
22036  */
22037 static void
22038 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22039     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22040     tcp_stack_t *tcps, conn_t *connp)
22041 {
22042 	ipha_t		*ipha = NULL;
22043 	ip6_t		*ip6h = NULL;
22044 	ushort_t	len;
22045 	tcph_t		*tcph;
22046 	int		i;
22047 	mblk_t		*ipsec_mp;
22048 	boolean_t	mctl_present;
22049 	ipic_t		*ipic;
22050 	ipaddr_t	v4addr;
22051 	in6_addr_t	v6addr;
22052 	int		addr_len;
22053 	void		*addr;
22054 	queue_t		*q = tcps->tcps_g_q;
22055 	tcp_t		*tcp;
22056 	cred_t		*cr;
22057 	pid_t		pid;
22058 	mblk_t		*nmp;
22059 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22060 
22061 	if (tcps->tcps_g_q == NULL) {
22062 		/*
22063 		 * For non-zero stackids the default queue isn't created
22064 		 * until the first open, thus there can be a need to send
22065 		 * a reset before then. But we can't do that, hence we just
22066 		 * drop the packet. Later during boot, when the default queue
22067 		 * has been setup, a retransmitted packet from the peer
22068 		 * will result in a reset.
22069 		 */
22070 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22071 		    GLOBAL_NETSTACKID);
22072 		freemsg(mp);
22073 		return;
22074 	}
22075 
22076 	if (connp != NULL)
22077 		tcp = connp->conn_tcp;
22078 	else
22079 		tcp = Q_TO_TCP(q);
22080 
22081 	if (!tcp_send_rst_chk(tcps)) {
22082 		tcps->tcps_rst_unsent++;
22083 		freemsg(mp);
22084 		return;
22085 	}
22086 
22087 	if (mp->b_datap->db_type == M_CTL) {
22088 		ipsec_mp = mp;
22089 		mp = mp->b_cont;
22090 		mctl_present = B_TRUE;
22091 	} else {
22092 		ipsec_mp = mp;
22093 		mctl_present = B_FALSE;
22094 	}
22095 
22096 	if (str && q && tcps->tcps_dbg) {
22097 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22098 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22099 		    "flags 0x%x",
22100 		    str, seq, ack, ctl);
22101 	}
22102 	if (mp->b_datap->db_ref != 1) {
22103 		mblk_t *mp1 = copyb(mp);
22104 		freemsg(mp);
22105 		mp = mp1;
22106 		if (!mp) {
22107 			if (mctl_present)
22108 				freeb(ipsec_mp);
22109 			return;
22110 		} else {
22111 			if (mctl_present) {
22112 				ipsec_mp->b_cont = mp;
22113 			} else {
22114 				ipsec_mp = mp;
22115 			}
22116 		}
22117 	} else if (mp->b_cont) {
22118 		freemsg(mp->b_cont);
22119 		mp->b_cont = NULL;
22120 	}
22121 	/*
22122 	 * We skip reversing source route here.
22123 	 * (for now we replace all IP options with EOL)
22124 	 */
22125 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22126 		ipha = (ipha_t *)mp->b_rptr;
22127 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22128 			mp->b_rptr[i] = IPOPT_EOL;
22129 		/*
22130 		 * Make sure that src address isn't flagrantly invalid.
22131 		 * Not all broadcast address checking for the src address
22132 		 * is possible, since we don't know the netmask of the src
22133 		 * addr.  No check for destination address is done, since
22134 		 * IP will not pass up a packet with a broadcast dest
22135 		 * address to TCP.  Similar checks are done below for IPv6.
22136 		 */
22137 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22138 		    CLASSD(ipha->ipha_src)) {
22139 			freemsg(ipsec_mp);
22140 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22141 			return;
22142 		}
22143 	} else {
22144 		ip6h = (ip6_t *)mp->b_rptr;
22145 
22146 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22147 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22148 			freemsg(ipsec_mp);
22149 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22150 			return;
22151 		}
22152 
22153 		/* Remove any extension headers assuming partial overlay */
22154 		if (ip_hdr_len > IPV6_HDR_LEN) {
22155 			uint8_t *to;
22156 
22157 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22158 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22159 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22160 			ip_hdr_len = IPV6_HDR_LEN;
22161 			ip6h = (ip6_t *)mp->b_rptr;
22162 			ip6h->ip6_nxt = IPPROTO_TCP;
22163 		}
22164 	}
22165 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22166 	if (tcph->th_flags[0] & TH_RST) {
22167 		freemsg(ipsec_mp);
22168 		return;
22169 	}
22170 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22171 	len = ip_hdr_len + sizeof (tcph_t);
22172 	mp->b_wptr = &mp->b_rptr[len];
22173 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22174 		ipha->ipha_length = htons(len);
22175 		/* Swap addresses */
22176 		v4addr = ipha->ipha_src;
22177 		ipha->ipha_src = ipha->ipha_dst;
22178 		ipha->ipha_dst = v4addr;
22179 		ipha->ipha_ident = 0;
22180 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22181 		addr_len = IP_ADDR_LEN;
22182 		addr = &v4addr;
22183 	} else {
22184 		/* No ip6i_t in this case */
22185 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22186 		/* Swap addresses */
22187 		v6addr = ip6h->ip6_src;
22188 		ip6h->ip6_src = ip6h->ip6_dst;
22189 		ip6h->ip6_dst = v6addr;
22190 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22191 		addr_len = IPV6_ADDR_LEN;
22192 		addr = &v6addr;
22193 	}
22194 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22195 	U32_TO_BE32(ack, tcph->th_ack);
22196 	U32_TO_BE32(seq, tcph->th_seq);
22197 	U16_TO_BE16(0, tcph->th_win);
22198 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22199 	tcph->th_flags[0] = (uint8_t)ctl;
22200 	if (ctl & TH_RST) {
22201 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22202 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22203 	}
22204 
22205 	/* IP trusts us to set up labels when required. */
22206 	if (is_system_labeled() && (cr = msg_getcred(mp, &pid)) != NULL &&
22207 	    crgetlabel(cr) != NULL) {
22208 		int err;
22209 
22210 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22211 			err = tsol_check_label(cr, &mp,
22212 			    tcp->tcp_connp->conn_mac_exempt,
22213 			    tcps->tcps_netstack->netstack_ip, pid);
22214 		else
22215 			err = tsol_check_label_v6(cr, &mp,
22216 			    tcp->tcp_connp->conn_mac_exempt,
22217 			    tcps->tcps_netstack->netstack_ip, pid);
22218 		if (mctl_present)
22219 			ipsec_mp->b_cont = mp;
22220 		else
22221 			ipsec_mp = mp;
22222 		if (err != 0) {
22223 			freemsg(ipsec_mp);
22224 			return;
22225 		}
22226 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22227 			ipha = (ipha_t *)mp->b_rptr;
22228 		} else {
22229 			ip6h = (ip6_t *)mp->b_rptr;
22230 		}
22231 	}
22232 
22233 	if (mctl_present) {
22234 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22235 
22236 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22237 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22238 			return;
22239 		}
22240 	}
22241 	if (zoneid == ALL_ZONES)
22242 		zoneid = GLOBAL_ZONEID;
22243 
22244 	/* Add the zoneid so ip_output routes it properly */
22245 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22246 		freemsg(ipsec_mp);
22247 		return;
22248 	}
22249 	ipsec_mp = nmp;
22250 
22251 	/*
22252 	 * NOTE:  one might consider tracing a TCP packet here, but
22253 	 * this function has no active TCP state and no tcp structure
22254 	 * that has a trace buffer.  If we traced here, we would have
22255 	 * to keep a local trace buffer in tcp_record_trace().
22256 	 *
22257 	 * TSol note: The mblk that contains the incoming packet was
22258 	 * reused by tcp_xmit_listener_reset, so it already contains
22259 	 * the right credentials and we don't need to call mblk_setcred.
22260 	 * Also the conn's cred is not right since it is associated
22261 	 * with tcps_g_q.
22262 	 */
22263 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22264 
22265 	/*
22266 	 * Tell IP to mark the IRE used for this destination temporary.
22267 	 * This way, we can limit our exposure to DoS attack because IP
22268 	 * creates an IRE for each destination.  If there are too many,
22269 	 * the time to do any routing lookup will be extremely long.  And
22270 	 * the lookup can be in interrupt context.
22271 	 *
22272 	 * Note that in normal circumstances, this marking should not
22273 	 * affect anything.  It would be nice if only 1 message is
22274 	 * needed to inform IP that the IRE created for this RST should
22275 	 * not be added to the cache table.  But there is currently
22276 	 * not such communication mechanism between TCP and IP.  So
22277 	 * the best we can do now is to send the advice ioctl to IP
22278 	 * to mark the IRE temporary.
22279 	 */
22280 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22281 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22282 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22283 	}
22284 }
22285 
22286 /*
22287  * Initiate closedown sequence on an active connection.  (May be called as
22288  * writer.)  Return value zero for OK return, non-zero for error return.
22289  */
22290 static int
22291 tcp_xmit_end(tcp_t *tcp)
22292 {
22293 	ipic_t	*ipic;
22294 	mblk_t	*mp;
22295 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22296 
22297 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22298 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22299 		/*
22300 		 * Invalid state, only states TCPS_SYN_RCVD,
22301 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22302 		 */
22303 		return (-1);
22304 	}
22305 
22306 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22307 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22308 	/*
22309 	 * If there is nothing more unsent, send the FIN now.
22310 	 * Otherwise, it will go out with the last segment.
22311 	 */
22312 	if (tcp->tcp_unsent == 0) {
22313 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22314 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22315 
22316 		if (mp) {
22317 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22318 		} else {
22319 			/*
22320 			 * Couldn't allocate msg.  Pretend we got it out.
22321 			 * Wait for rexmit timeout.
22322 			 */
22323 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22324 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22325 		}
22326 
22327 		/*
22328 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22329 		 * changed.
22330 		 */
22331 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22332 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22333 		}
22334 	} else {
22335 		/*
22336 		 * If tcp->tcp_cork is set, then the data will not get sent,
22337 		 * so we have to check that and unset it first.
22338 		 */
22339 		if (tcp->tcp_cork)
22340 			tcp->tcp_cork = B_FALSE;
22341 		tcp_wput_data(tcp, NULL, B_FALSE);
22342 	}
22343 
22344 	/*
22345 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22346 	 * is 0, don't update the cache.
22347 	 */
22348 	if (tcps->tcps_rtt_updates == 0 ||
22349 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22350 		return (0);
22351 
22352 	/*
22353 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22354 	 * different from the destination.
22355 	 */
22356 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22357 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22358 			return (0);
22359 		}
22360 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22361 		    &ipic);
22362 	} else {
22363 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22364 		    &tcp->tcp_ip6h->ip6_dst))) {
22365 			return (0);
22366 		}
22367 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22368 		    &ipic);
22369 	}
22370 
22371 	/* Record route attributes in the IRE for use by future connections. */
22372 	if (mp == NULL)
22373 		return (0);
22374 
22375 	/*
22376 	 * We do not have a good algorithm to update ssthresh at this time.
22377 	 * So don't do any update.
22378 	 */
22379 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22380 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22381 
22382 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22383 
22384 	return (0);
22385 }
22386 
22387 /* ARGSUSED */
22388 void
22389 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
22390 {
22391 	conn_t *connp = (conn_t *)arg;
22392 	mblk_t *mp1;
22393 	tcp_t *tcp = connp->conn_tcp;
22394 	tcp_xmit_reset_event_t *eventp;
22395 
22396 	ASSERT(mp->b_datap->db_type == M_PROTO &&
22397 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
22398 
22399 	if (tcp->tcp_state != TCPS_LISTEN) {
22400 		freemsg(mp);
22401 		return;
22402 	}
22403 
22404 	mp1 = mp->b_cont;
22405 	mp->b_cont = NULL;
22406 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
22407 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
22408 	    connp->conn_netstack);
22409 
22410 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
22411 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
22412 	freemsg(mp);
22413 }
22414 
22415 /*
22416  * Generate a "no listener here" RST in response to an "unknown" segment.
22417  * connp is set by caller when RST is in response to an unexpected
22418  * inbound packet for which there is active tcp state in the system.
22419  * Note that we are reusing the incoming mp to construct the outgoing RST.
22420  */
22421 void
22422 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22423     tcp_stack_t *tcps, conn_t *connp)
22424 {
22425 	uchar_t		*rptr;
22426 	uint32_t	seg_len;
22427 	tcph_t		*tcph;
22428 	uint32_t	seg_seq;
22429 	uint32_t	seg_ack;
22430 	uint_t		flags;
22431 	mblk_t		*ipsec_mp;
22432 	ipha_t 		*ipha;
22433 	ip6_t 		*ip6h;
22434 	boolean_t	mctl_present = B_FALSE;
22435 	boolean_t	check = B_TRUE;
22436 	boolean_t	policy_present;
22437 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22438 
22439 	TCP_STAT(tcps, tcp_no_listener);
22440 
22441 	ipsec_mp = mp;
22442 
22443 	if (mp->b_datap->db_type == M_CTL) {
22444 		ipsec_in_t *ii;
22445 
22446 		mctl_present = B_TRUE;
22447 		mp = mp->b_cont;
22448 
22449 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22450 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22451 		if (ii->ipsec_in_dont_check) {
22452 			check = B_FALSE;
22453 			if (!ii->ipsec_in_secure) {
22454 				freeb(ipsec_mp);
22455 				mctl_present = B_FALSE;
22456 				ipsec_mp = mp;
22457 			}
22458 		}
22459 	}
22460 
22461 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22462 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22463 		ipha = (ipha_t *)mp->b_rptr;
22464 		ip6h = NULL;
22465 	} else {
22466 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22467 		ipha = NULL;
22468 		ip6h = (ip6_t *)mp->b_rptr;
22469 	}
22470 
22471 	if (check && policy_present) {
22472 		/*
22473 		 * The conn_t parameter is NULL because we already know
22474 		 * nobody's home.
22475 		 */
22476 		ipsec_mp = ipsec_check_global_policy(
22477 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22478 		    tcps->tcps_netstack);
22479 		if (ipsec_mp == NULL)
22480 			return;
22481 	}
22482 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22483 		DTRACE_PROBE2(
22484 		    tx__ip__log__error__nolistener__tcp,
22485 		    char *, "Could not reply with RST to mp(1)",
22486 		    mblk_t *, mp);
22487 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22488 		freemsg(ipsec_mp);
22489 		return;
22490 	}
22491 
22492 	rptr = mp->b_rptr;
22493 
22494 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22495 	seg_seq = BE32_TO_U32(tcph->th_seq);
22496 	seg_ack = BE32_TO_U32(tcph->th_ack);
22497 	flags = tcph->th_flags[0];
22498 
22499 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22500 	if (flags & TH_RST) {
22501 		freemsg(ipsec_mp);
22502 	} else if (flags & TH_ACK) {
22503 		tcp_xmit_early_reset("no tcp, reset",
22504 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22505 		    connp);
22506 	} else {
22507 		if (flags & TH_SYN) {
22508 			seg_len++;
22509 		} else {
22510 			/*
22511 			 * Here we violate the RFC.  Note that a normal
22512 			 * TCP will never send a segment without the ACK
22513 			 * flag, except for RST or SYN segment.  This
22514 			 * segment is neither.  Just drop it on the
22515 			 * floor.
22516 			 */
22517 			freemsg(ipsec_mp);
22518 			tcps->tcps_rst_unsent++;
22519 			return;
22520 		}
22521 
22522 		tcp_xmit_early_reset("no tcp, reset/ack",
22523 		    ipsec_mp, 0, seg_seq + seg_len,
22524 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22525 	}
22526 }
22527 
22528 /*
22529  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22530  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22531  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22532  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22533  * otherwise it will dup partial mblks.)
22534  * Otherwise, an appropriate ACK packet will be generated.  This
22535  * routine is not usually called to send new data for the first time.  It
22536  * is mostly called out of the timer for retransmits, and to generate ACKs.
22537  *
22538  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22539  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22540  * of the original mblk chain will be returned in *offset and *end_mp.
22541  */
22542 mblk_t *
22543 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22544     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22545     boolean_t rexmit)
22546 {
22547 	int	data_length;
22548 	int32_t	off = 0;
22549 	uint_t	flags;
22550 	mblk_t	*mp1;
22551 	mblk_t	*mp2;
22552 	uchar_t	*rptr;
22553 	tcph_t	*tcph;
22554 	int32_t	num_sack_blk = 0;
22555 	int32_t	sack_opt_len = 0;
22556 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22557 
22558 	/* Allocate for our maximum TCP header + link-level */
22559 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22560 	    tcps->tcps_wroff_xtra, BPRI_MED);
22561 	if (!mp1)
22562 		return (NULL);
22563 	data_length = 0;
22564 
22565 	/*
22566 	 * Note that tcp_mss has been adjusted to take into account the
22567 	 * timestamp option if applicable.  Because SACK options do not
22568 	 * appear in every TCP segments and they are of variable lengths,
22569 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22570 	 * the actual segment length when we need to send a segment which
22571 	 * includes SACK options.
22572 	 */
22573 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22574 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22575 		    tcp->tcp_num_sack_blk);
22576 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22577 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22578 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22579 			max_to_send -= sack_opt_len;
22580 	}
22581 
22582 	if (offset != NULL) {
22583 		off = *offset;
22584 		/* We use offset as an indicator that end_mp is not NULL. */
22585 		*end_mp = NULL;
22586 	}
22587 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22588 		/* This could be faster with cooperation from downstream */
22589 		if (mp2 != mp1 && !sendall &&
22590 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22591 		    max_to_send)
22592 			/*
22593 			 * Don't send the next mblk since the whole mblk
22594 			 * does not fit.
22595 			 */
22596 			break;
22597 		mp2->b_cont = dupb(mp);
22598 		mp2 = mp2->b_cont;
22599 		if (!mp2) {
22600 			freemsg(mp1);
22601 			return (NULL);
22602 		}
22603 		mp2->b_rptr += off;
22604 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22605 		    (uintptr_t)INT_MAX);
22606 
22607 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22608 		if (data_length > max_to_send) {
22609 			mp2->b_wptr -= data_length - max_to_send;
22610 			data_length = max_to_send;
22611 			off = mp2->b_wptr - mp->b_rptr;
22612 			break;
22613 		} else {
22614 			off = 0;
22615 		}
22616 	}
22617 	if (offset != NULL) {
22618 		*offset = off;
22619 		*end_mp = mp;
22620 	}
22621 	if (seg_len != NULL) {
22622 		*seg_len = data_length;
22623 	}
22624 
22625 	/* Update the latest receive window size in TCP header. */
22626 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22627 	    tcp->tcp_tcph->th_win);
22628 
22629 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22630 	mp1->b_rptr = rptr;
22631 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22632 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22633 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22634 	U32_TO_ABE32(seq, tcph->th_seq);
22635 
22636 	/*
22637 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22638 	 * that this function was called from tcp_wput_data. Thus, when called
22639 	 * to retransmit data the setting of the PUSH bit may appear some
22640 	 * what random in that it might get set when it should not. This
22641 	 * should not pose any performance issues.
22642 	 */
22643 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22644 	    tcp->tcp_unsent == data_length)) {
22645 		flags = TH_ACK | TH_PUSH;
22646 	} else {
22647 		flags = TH_ACK;
22648 	}
22649 
22650 	if (tcp->tcp_ecn_ok) {
22651 		if (tcp->tcp_ecn_echo_on)
22652 			flags |= TH_ECE;
22653 
22654 		/*
22655 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22656 		 * There is no TCP flow control for non-data segments, and
22657 		 * only data segment is transmitted reliably.
22658 		 */
22659 		if (data_length > 0 && !rexmit) {
22660 			SET_ECT(tcp, rptr);
22661 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22662 				flags |= TH_CWR;
22663 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22664 			}
22665 		}
22666 	}
22667 
22668 	if (tcp->tcp_valid_bits) {
22669 		uint32_t u1;
22670 
22671 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22672 		    seq == tcp->tcp_iss) {
22673 			uchar_t	*wptr;
22674 
22675 			/*
22676 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22677 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22678 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22679 			 * our SYN is not ack'ed but the app closes this
22680 			 * TCP connection.
22681 			 */
22682 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22683 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22684 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22685 
22686 			/*
22687 			 * Tack on the MSS option.  It is always needed
22688 			 * for both active and passive open.
22689 			 *
22690 			 * MSS option value should be interface MTU - MIN
22691 			 * TCP/IP header according to RFC 793 as it means
22692 			 * the maximum segment size TCP can receive.  But
22693 			 * to get around some broken middle boxes/end hosts
22694 			 * out there, we allow the option value to be the
22695 			 * same as the MSS option size on the peer side.
22696 			 * In this way, the other side will not send
22697 			 * anything larger than they can receive.
22698 			 *
22699 			 * Note that for SYN_SENT state, the ndd param
22700 			 * tcp_use_smss_as_mss_opt has no effect as we
22701 			 * don't know the peer's MSS option value. So
22702 			 * the only case we need to take care of is in
22703 			 * SYN_RCVD state, which is done later.
22704 			 */
22705 			wptr = mp1->b_wptr;
22706 			wptr[0] = TCPOPT_MAXSEG;
22707 			wptr[1] = TCPOPT_MAXSEG_LEN;
22708 			wptr += 2;
22709 			u1 = tcp->tcp_if_mtu -
22710 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22711 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22712 			    TCP_MIN_HEADER_LENGTH;
22713 			U16_TO_BE16(u1, wptr);
22714 			mp1->b_wptr = wptr + 2;
22715 			/* Update the offset to cover the additional word */
22716 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22717 
22718 			/*
22719 			 * Note that the following way of filling in
22720 			 * TCP options are not optimal.  Some NOPs can
22721 			 * be saved.  But there is no need at this time
22722 			 * to optimize it.  When it is needed, we will
22723 			 * do it.
22724 			 */
22725 			switch (tcp->tcp_state) {
22726 			case TCPS_SYN_SENT:
22727 				flags = TH_SYN;
22728 
22729 				if (tcp->tcp_snd_ts_ok) {
22730 					uint32_t llbolt = (uint32_t)lbolt;
22731 
22732 					wptr = mp1->b_wptr;
22733 					wptr[0] = TCPOPT_NOP;
22734 					wptr[1] = TCPOPT_NOP;
22735 					wptr[2] = TCPOPT_TSTAMP;
22736 					wptr[3] = TCPOPT_TSTAMP_LEN;
22737 					wptr += 4;
22738 					U32_TO_BE32(llbolt, wptr);
22739 					wptr += 4;
22740 					ASSERT(tcp->tcp_ts_recent == 0);
22741 					U32_TO_BE32(0L, wptr);
22742 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22743 					tcph->th_offset_and_rsrvd[0] +=
22744 					    (3 << 4);
22745 				}
22746 
22747 				/*
22748 				 * Set up all the bits to tell other side
22749 				 * we are ECN capable.
22750 				 */
22751 				if (tcp->tcp_ecn_ok) {
22752 					flags |= (TH_ECE | TH_CWR);
22753 				}
22754 				break;
22755 			case TCPS_SYN_RCVD:
22756 				flags |= TH_SYN;
22757 
22758 				/*
22759 				 * Reset the MSS option value to be SMSS
22760 				 * We should probably add back the bytes
22761 				 * for timestamp option and IPsec.  We
22762 				 * don't do that as this is a workaround
22763 				 * for broken middle boxes/end hosts, it
22764 				 * is better for us to be more cautious.
22765 				 * They may not take these things into
22766 				 * account in their SMSS calculation.  Thus
22767 				 * the peer's calculated SMSS may be smaller
22768 				 * than what it can be.  This should be OK.
22769 				 */
22770 				if (tcps->tcps_use_smss_as_mss_opt) {
22771 					u1 = tcp->tcp_mss;
22772 					U16_TO_BE16(u1, wptr);
22773 				}
22774 
22775 				/*
22776 				 * If the other side is ECN capable, reply
22777 				 * that we are also ECN capable.
22778 				 */
22779 				if (tcp->tcp_ecn_ok)
22780 					flags |= TH_ECE;
22781 				break;
22782 			default:
22783 				/*
22784 				 * The above ASSERT() makes sure that this
22785 				 * must be FIN-WAIT-1 state.  Our SYN has
22786 				 * not been ack'ed so retransmit it.
22787 				 */
22788 				flags |= TH_SYN;
22789 				break;
22790 			}
22791 
22792 			if (tcp->tcp_snd_ws_ok) {
22793 				wptr = mp1->b_wptr;
22794 				wptr[0] =  TCPOPT_NOP;
22795 				wptr[1] =  TCPOPT_WSCALE;
22796 				wptr[2] =  TCPOPT_WS_LEN;
22797 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22798 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22799 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22800 			}
22801 
22802 			if (tcp->tcp_snd_sack_ok) {
22803 				wptr = mp1->b_wptr;
22804 				wptr[0] = TCPOPT_NOP;
22805 				wptr[1] = TCPOPT_NOP;
22806 				wptr[2] = TCPOPT_SACK_PERMITTED;
22807 				wptr[3] = TCPOPT_SACK_OK_LEN;
22808 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22809 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22810 			}
22811 
22812 			/* allocb() of adequate mblk assures space */
22813 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22814 			    (uintptr_t)INT_MAX);
22815 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22816 			/*
22817 			 * Get IP set to checksum on our behalf
22818 			 * Include the adjustment for a source route if any.
22819 			 */
22820 			u1 += tcp->tcp_sum;
22821 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22822 			U16_TO_BE16(u1, tcph->th_sum);
22823 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22824 		}
22825 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22826 		    (seq + data_length) == tcp->tcp_fss) {
22827 			if (!tcp->tcp_fin_acked) {
22828 				flags |= TH_FIN;
22829 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22830 			}
22831 			if (!tcp->tcp_fin_sent) {
22832 				tcp->tcp_fin_sent = B_TRUE;
22833 				switch (tcp->tcp_state) {
22834 				case TCPS_SYN_RCVD:
22835 				case TCPS_ESTABLISHED:
22836 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22837 					break;
22838 				case TCPS_CLOSE_WAIT:
22839 					tcp->tcp_state = TCPS_LAST_ACK;
22840 					break;
22841 				}
22842 				if (tcp->tcp_suna == tcp->tcp_snxt)
22843 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22844 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22845 			}
22846 		}
22847 		/*
22848 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22849 		 * is smaller than seq, u1 will become a very huge value.
22850 		 * So the comparison will fail.  Also note that tcp_urp
22851 		 * should be positive, see RFC 793 page 17.
22852 		 */
22853 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22854 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22855 		    u1 < (uint32_t)(64 * 1024)) {
22856 			flags |= TH_URG;
22857 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
22858 			U32_TO_ABE16(u1, tcph->th_urp);
22859 		}
22860 	}
22861 	tcph->th_flags[0] = (uchar_t)flags;
22862 	tcp->tcp_rack = tcp->tcp_rnxt;
22863 	tcp->tcp_rack_cnt = 0;
22864 
22865 	if (tcp->tcp_snd_ts_ok) {
22866 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22867 			uint32_t llbolt = (uint32_t)lbolt;
22868 
22869 			U32_TO_BE32(llbolt,
22870 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22871 			U32_TO_BE32(tcp->tcp_ts_recent,
22872 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22873 		}
22874 	}
22875 
22876 	if (num_sack_blk > 0) {
22877 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22878 		sack_blk_t *tmp;
22879 		int32_t	i;
22880 
22881 		wptr[0] = TCPOPT_NOP;
22882 		wptr[1] = TCPOPT_NOP;
22883 		wptr[2] = TCPOPT_SACK;
22884 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22885 		    sizeof (sack_blk_t);
22886 		wptr += TCPOPT_REAL_SACK_LEN;
22887 
22888 		tmp = tcp->tcp_sack_list;
22889 		for (i = 0; i < num_sack_blk; i++) {
22890 			U32_TO_BE32(tmp[i].begin, wptr);
22891 			wptr += sizeof (tcp_seq);
22892 			U32_TO_BE32(tmp[i].end, wptr);
22893 			wptr += sizeof (tcp_seq);
22894 		}
22895 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22896 	}
22897 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22898 	data_length += (int)(mp1->b_wptr - rptr);
22899 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22900 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22901 	} else {
22902 		ip6_t *ip6 = (ip6_t *)(rptr +
22903 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22904 		    sizeof (ip6i_t) : 0));
22905 
22906 		ip6->ip6_plen = htons(data_length -
22907 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22908 	}
22909 
22910 	/*
22911 	 * Prime pump for IP
22912 	 * Include the adjustment for a source route if any.
22913 	 */
22914 	data_length -= tcp->tcp_ip_hdr_len;
22915 	data_length += tcp->tcp_sum;
22916 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22917 	U16_TO_ABE16(data_length, tcph->th_sum);
22918 	if (tcp->tcp_ip_forward_progress) {
22919 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22920 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22921 		tcp->tcp_ip_forward_progress = B_FALSE;
22922 	}
22923 	return (mp1);
22924 }
22925 
22926 /* This function handles the push timeout. */
22927 void
22928 tcp_push_timer(void *arg)
22929 {
22930 	conn_t	*connp = (conn_t *)arg;
22931 	tcp_t *tcp = connp->conn_tcp;
22932 
22933 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
22934 
22935 	ASSERT(tcp->tcp_listener == NULL);
22936 
22937 	ASSERT(!IPCL_IS_NONSTR(connp));
22938 
22939 	tcp->tcp_push_tid = 0;
22940 
22941 	if (tcp->tcp_rcv_list != NULL &&
22942 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
22943 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22944 }
22945 
22946 /*
22947  * This function handles delayed ACK timeout.
22948  */
22949 static void
22950 tcp_ack_timer(void *arg)
22951 {
22952 	conn_t	*connp = (conn_t *)arg;
22953 	tcp_t *tcp = connp->conn_tcp;
22954 	mblk_t *mp;
22955 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22956 
22957 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
22958 
22959 	tcp->tcp_ack_tid = 0;
22960 
22961 	if (tcp->tcp_fused)
22962 		return;
22963 
22964 	/*
22965 	 * Do not send ACK if there is no outstanding unack'ed data.
22966 	 */
22967 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22968 		return;
22969 	}
22970 
22971 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22972 		/*
22973 		 * Make sure we don't allow deferred ACKs to result in
22974 		 * timer-based ACKing.  If we have held off an ACK
22975 		 * when there was more than an mss here, and the timer
22976 		 * goes off, we have to worry about the possibility
22977 		 * that the sender isn't doing slow-start, or is out
22978 		 * of step with us for some other reason.  We fall
22979 		 * permanently back in the direction of
22980 		 * ACK-every-other-packet as suggested in RFC 1122.
22981 		 */
22982 		if (tcp->tcp_rack_abs_max > 2)
22983 			tcp->tcp_rack_abs_max--;
22984 		tcp->tcp_rack_cur_max = 2;
22985 	}
22986 	mp = tcp_ack_mp(tcp);
22987 
22988 	if (mp != NULL) {
22989 		BUMP_LOCAL(tcp->tcp_obsegs);
22990 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22991 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
22992 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22993 	}
22994 }
22995 
22996 
22997 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22998 static mblk_t *
22999 tcp_ack_mp(tcp_t *tcp)
23000 {
23001 	uint32_t	seq_no;
23002 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23003 
23004 	/*
23005 	 * There are a few cases to be considered while setting the sequence no.
23006 	 * Essentially, we can come here while processing an unacceptable pkt
23007 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23008 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23009 	 * If we are here for a zero window probe, stick with suna. In all
23010 	 * other cases, we check if suna + swnd encompasses snxt and set
23011 	 * the sequence number to snxt, if so. If snxt falls outside the
23012 	 * window (the receiver probably shrunk its window), we will go with
23013 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23014 	 * receiver.
23015 	 */
23016 	if (tcp->tcp_zero_win_probe) {
23017 		seq_no = tcp->tcp_suna;
23018 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23019 		ASSERT(tcp->tcp_swnd == 0);
23020 		seq_no = tcp->tcp_snxt;
23021 	} else {
23022 		seq_no = SEQ_GT(tcp->tcp_snxt,
23023 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23024 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23025 	}
23026 
23027 	if (tcp->tcp_valid_bits) {
23028 		/*
23029 		 * For the complex case where we have to send some
23030 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23031 		 */
23032 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23033 		    NULL, B_FALSE));
23034 	} else {
23035 		/* Generate a simple ACK */
23036 		int	data_length;
23037 		uchar_t	*rptr;
23038 		tcph_t	*tcph;
23039 		mblk_t	*mp1;
23040 		int32_t	tcp_hdr_len;
23041 		int32_t	tcp_tcp_hdr_len;
23042 		int32_t	num_sack_blk = 0;
23043 		int32_t sack_opt_len;
23044 
23045 		/*
23046 		 * Allocate space for TCP + IP headers
23047 		 * and link-level header
23048 		 */
23049 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23050 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23051 			    tcp->tcp_num_sack_blk);
23052 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23053 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23054 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23055 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23056 		} else {
23057 			tcp_hdr_len = tcp->tcp_hdr_len;
23058 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23059 		}
23060 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23061 		if (!mp1)
23062 			return (NULL);
23063 
23064 		/* Update the latest receive window size in TCP header. */
23065 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23066 		    tcp->tcp_tcph->th_win);
23067 		/* copy in prototype TCP + IP header */
23068 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23069 		mp1->b_rptr = rptr;
23070 		mp1->b_wptr = rptr + tcp_hdr_len;
23071 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23072 
23073 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23074 
23075 		/* Set the TCP sequence number. */
23076 		U32_TO_ABE32(seq_no, tcph->th_seq);
23077 
23078 		/* Set up the TCP flag field. */
23079 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23080 		if (tcp->tcp_ecn_echo_on)
23081 			tcph->th_flags[0] |= TH_ECE;
23082 
23083 		tcp->tcp_rack = tcp->tcp_rnxt;
23084 		tcp->tcp_rack_cnt = 0;
23085 
23086 		/* fill in timestamp option if in use */
23087 		if (tcp->tcp_snd_ts_ok) {
23088 			uint32_t llbolt = (uint32_t)lbolt;
23089 
23090 			U32_TO_BE32(llbolt,
23091 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23092 			U32_TO_BE32(tcp->tcp_ts_recent,
23093 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23094 		}
23095 
23096 		/* Fill in SACK options */
23097 		if (num_sack_blk > 0) {
23098 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23099 			sack_blk_t *tmp;
23100 			int32_t	i;
23101 
23102 			wptr[0] = TCPOPT_NOP;
23103 			wptr[1] = TCPOPT_NOP;
23104 			wptr[2] = TCPOPT_SACK;
23105 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23106 			    sizeof (sack_blk_t);
23107 			wptr += TCPOPT_REAL_SACK_LEN;
23108 
23109 			tmp = tcp->tcp_sack_list;
23110 			for (i = 0; i < num_sack_blk; i++) {
23111 				U32_TO_BE32(tmp[i].begin, wptr);
23112 				wptr += sizeof (tcp_seq);
23113 				U32_TO_BE32(tmp[i].end, wptr);
23114 				wptr += sizeof (tcp_seq);
23115 			}
23116 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23117 			    << 4);
23118 		}
23119 
23120 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23121 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23122 		} else {
23123 			/* Check for ip6i_t header in sticky hdrs */
23124 			ip6_t *ip6 = (ip6_t *)(rptr +
23125 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23126 			    sizeof (ip6i_t) : 0));
23127 
23128 			ip6->ip6_plen = htons(tcp_hdr_len -
23129 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23130 		}
23131 
23132 		/*
23133 		 * Prime pump for checksum calculation in IP.  Include the
23134 		 * adjustment for a source route if any.
23135 		 */
23136 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23137 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23138 		U16_TO_ABE16(data_length, tcph->th_sum);
23139 
23140 		if (tcp->tcp_ip_forward_progress) {
23141 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23142 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23143 			tcp->tcp_ip_forward_progress = B_FALSE;
23144 		}
23145 		return (mp1);
23146 	}
23147 }
23148 
23149 /*
23150  * Hash list insertion routine for tcp_t structures. Each hash bucket
23151  * contains a list of tcp_t entries, and each entry is bound to a unique
23152  * port. If there are multiple tcp_t's that are bound to the same port, then
23153  * one of them will be linked into the hash bucket list, and the rest will
23154  * hang off of that one entry. For each port, entries bound to a specific IP
23155  * address will be inserted before those those bound to INADDR_ANY.
23156  */
23157 static void
23158 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23159 {
23160 	tcp_t	**tcpp;
23161 	tcp_t	*tcpnext;
23162 	tcp_t	*tcphash;
23163 
23164 	if (tcp->tcp_ptpbhn != NULL) {
23165 		ASSERT(!caller_holds_lock);
23166 		tcp_bind_hash_remove(tcp);
23167 	}
23168 	tcpp = &tbf->tf_tcp;
23169 	if (!caller_holds_lock) {
23170 		mutex_enter(&tbf->tf_lock);
23171 	} else {
23172 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23173 	}
23174 	tcphash = tcpp[0];
23175 	tcpnext = NULL;
23176 	if (tcphash != NULL) {
23177 		/* Look for an entry using the same port */
23178 		while ((tcphash = tcpp[0]) != NULL &&
23179 		    tcp->tcp_lport != tcphash->tcp_lport)
23180 			tcpp = &(tcphash->tcp_bind_hash);
23181 
23182 		/* The port was not found, just add to the end */
23183 		if (tcphash == NULL)
23184 			goto insert;
23185 
23186 		/*
23187 		 * OK, there already exists an entry bound to the
23188 		 * same port.
23189 		 *
23190 		 * If the new tcp bound to the INADDR_ANY address
23191 		 * and the first one in the list is not bound to
23192 		 * INADDR_ANY we skip all entries until we find the
23193 		 * first one bound to INADDR_ANY.
23194 		 * This makes sure that applications binding to a
23195 		 * specific address get preference over those binding to
23196 		 * INADDR_ANY.
23197 		 */
23198 		tcpnext = tcphash;
23199 		tcphash = NULL;
23200 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23201 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23202 			while ((tcpnext = tcpp[0]) != NULL &&
23203 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23204 				tcpp = &(tcpnext->tcp_bind_hash_port);
23205 
23206 			if (tcpnext) {
23207 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23208 				tcphash = tcpnext->tcp_bind_hash;
23209 				if (tcphash != NULL) {
23210 					tcphash->tcp_ptpbhn =
23211 					    &(tcp->tcp_bind_hash);
23212 					tcpnext->tcp_bind_hash = NULL;
23213 				}
23214 			}
23215 		} else {
23216 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23217 			tcphash = tcpnext->tcp_bind_hash;
23218 			if (tcphash != NULL) {
23219 				tcphash->tcp_ptpbhn =
23220 				    &(tcp->tcp_bind_hash);
23221 				tcpnext->tcp_bind_hash = NULL;
23222 			}
23223 		}
23224 	}
23225 insert:
23226 	tcp->tcp_bind_hash_port = tcpnext;
23227 	tcp->tcp_bind_hash = tcphash;
23228 	tcp->tcp_ptpbhn = tcpp;
23229 	tcpp[0] = tcp;
23230 	if (!caller_holds_lock)
23231 		mutex_exit(&tbf->tf_lock);
23232 }
23233 
23234 /*
23235  * Hash list removal routine for tcp_t structures.
23236  */
23237 static void
23238 tcp_bind_hash_remove(tcp_t *tcp)
23239 {
23240 	tcp_t	*tcpnext;
23241 	kmutex_t *lockp;
23242 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23243 
23244 	if (tcp->tcp_ptpbhn == NULL)
23245 		return;
23246 
23247 	/*
23248 	 * Extract the lock pointer in case there are concurrent
23249 	 * hash_remove's for this instance.
23250 	 */
23251 	ASSERT(tcp->tcp_lport != 0);
23252 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23253 
23254 	ASSERT(lockp != NULL);
23255 	mutex_enter(lockp);
23256 	if (tcp->tcp_ptpbhn) {
23257 		tcpnext = tcp->tcp_bind_hash_port;
23258 		if (tcpnext != NULL) {
23259 			tcp->tcp_bind_hash_port = NULL;
23260 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23261 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23262 			if (tcpnext->tcp_bind_hash != NULL) {
23263 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23264 				    &(tcpnext->tcp_bind_hash);
23265 				tcp->tcp_bind_hash = NULL;
23266 			}
23267 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23268 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23269 			tcp->tcp_bind_hash = NULL;
23270 		}
23271 		*tcp->tcp_ptpbhn = tcpnext;
23272 		tcp->tcp_ptpbhn = NULL;
23273 	}
23274 	mutex_exit(lockp);
23275 }
23276 
23277 
23278 /*
23279  * Hash list lookup routine for tcp_t structures.
23280  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23281  */
23282 static tcp_t *
23283 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23284 {
23285 	tf_t	*tf;
23286 	tcp_t	*tcp;
23287 
23288 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23289 	mutex_enter(&tf->tf_lock);
23290 	for (tcp = tf->tf_tcp; tcp != NULL;
23291 	    tcp = tcp->tcp_acceptor_hash) {
23292 		if (tcp->tcp_acceptor_id == id) {
23293 			CONN_INC_REF(tcp->tcp_connp);
23294 			mutex_exit(&tf->tf_lock);
23295 			return (tcp);
23296 		}
23297 	}
23298 	mutex_exit(&tf->tf_lock);
23299 	return (NULL);
23300 }
23301 
23302 
23303 /*
23304  * Hash list insertion routine for tcp_t structures.
23305  */
23306 void
23307 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23308 {
23309 	tf_t	*tf;
23310 	tcp_t	**tcpp;
23311 	tcp_t	*tcpnext;
23312 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23313 
23314 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23315 
23316 	if (tcp->tcp_ptpahn != NULL)
23317 		tcp_acceptor_hash_remove(tcp);
23318 	tcpp = &tf->tf_tcp;
23319 	mutex_enter(&tf->tf_lock);
23320 	tcpnext = tcpp[0];
23321 	if (tcpnext)
23322 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23323 	tcp->tcp_acceptor_hash = tcpnext;
23324 	tcp->tcp_ptpahn = tcpp;
23325 	tcpp[0] = tcp;
23326 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23327 	mutex_exit(&tf->tf_lock);
23328 }
23329 
23330 /*
23331  * Hash list removal routine for tcp_t structures.
23332  */
23333 static void
23334 tcp_acceptor_hash_remove(tcp_t *tcp)
23335 {
23336 	tcp_t	*tcpnext;
23337 	kmutex_t *lockp;
23338 
23339 	/*
23340 	 * Extract the lock pointer in case there are concurrent
23341 	 * hash_remove's for this instance.
23342 	 */
23343 	lockp = tcp->tcp_acceptor_lockp;
23344 
23345 	if (tcp->tcp_ptpahn == NULL)
23346 		return;
23347 
23348 	ASSERT(lockp != NULL);
23349 	mutex_enter(lockp);
23350 	if (tcp->tcp_ptpahn) {
23351 		tcpnext = tcp->tcp_acceptor_hash;
23352 		if (tcpnext) {
23353 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23354 			tcp->tcp_acceptor_hash = NULL;
23355 		}
23356 		*tcp->tcp_ptpahn = tcpnext;
23357 		tcp->tcp_ptpahn = NULL;
23358 	}
23359 	mutex_exit(lockp);
23360 	tcp->tcp_acceptor_lockp = NULL;
23361 }
23362 
23363 /*
23364  * Type three generator adapted from the random() function in 4.4 BSD:
23365  */
23366 
23367 /*
23368  * Copyright (c) 1983, 1993
23369  *	The Regents of the University of California.  All rights reserved.
23370  *
23371  * Redistribution and use in source and binary forms, with or without
23372  * modification, are permitted provided that the following conditions
23373  * are met:
23374  * 1. Redistributions of source code must retain the above copyright
23375  *    notice, this list of conditions and the following disclaimer.
23376  * 2. Redistributions in binary form must reproduce the above copyright
23377  *    notice, this list of conditions and the following disclaimer in the
23378  *    documentation and/or other materials provided with the distribution.
23379  * 3. All advertising materials mentioning features or use of this software
23380  *    must display the following acknowledgement:
23381  *	This product includes software developed by the University of
23382  *	California, Berkeley and its contributors.
23383  * 4. Neither the name of the University nor the names of its contributors
23384  *    may be used to endorse or promote products derived from this software
23385  *    without specific prior written permission.
23386  *
23387  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23388  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23389  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23390  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23391  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23392  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23393  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23394  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23395  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23396  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23397  * SUCH DAMAGE.
23398  */
23399 
23400 /* Type 3 -- x**31 + x**3 + 1 */
23401 #define	DEG_3		31
23402 #define	SEP_3		3
23403 
23404 
23405 /* Protected by tcp_random_lock */
23406 static int tcp_randtbl[DEG_3 + 1];
23407 
23408 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23409 static int *tcp_random_rptr = &tcp_randtbl[1];
23410 
23411 static int *tcp_random_state = &tcp_randtbl[1];
23412 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23413 
23414 kmutex_t tcp_random_lock;
23415 
23416 void
23417 tcp_random_init(void)
23418 {
23419 	int i;
23420 	hrtime_t hrt;
23421 	time_t wallclock;
23422 	uint64_t result;
23423 
23424 	/*
23425 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23426 	 * a longlong, which may contain resolution down to nanoseconds.
23427 	 * The current time will either be a 32-bit or a 64-bit quantity.
23428 	 * XOR the two together in a 64-bit result variable.
23429 	 * Convert the result to a 32-bit value by multiplying the high-order
23430 	 * 32-bits by the low-order 32-bits.
23431 	 */
23432 
23433 	hrt = gethrtime();
23434 	(void) drv_getparm(TIME, &wallclock);
23435 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23436 	mutex_enter(&tcp_random_lock);
23437 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23438 	    (result & 0xffffffff);
23439 
23440 	for (i = 1; i < DEG_3; i++)
23441 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23442 		    + 12345;
23443 	tcp_random_fptr = &tcp_random_state[SEP_3];
23444 	tcp_random_rptr = &tcp_random_state[0];
23445 	mutex_exit(&tcp_random_lock);
23446 	for (i = 0; i < 10 * DEG_3; i++)
23447 		(void) tcp_random();
23448 }
23449 
23450 /*
23451  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23452  * This range is selected to be approximately centered on TCP_ISS / 2,
23453  * and easy to compute. We get this value by generating a 32-bit random
23454  * number, selecting out the high-order 17 bits, and then adding one so
23455  * that we never return zero.
23456  */
23457 int
23458 tcp_random(void)
23459 {
23460 	int i;
23461 
23462 	mutex_enter(&tcp_random_lock);
23463 	*tcp_random_fptr += *tcp_random_rptr;
23464 
23465 	/*
23466 	 * The high-order bits are more random than the low-order bits,
23467 	 * so we select out the high-order 17 bits and add one so that
23468 	 * we never return zero.
23469 	 */
23470 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23471 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23472 		tcp_random_fptr = tcp_random_state;
23473 		++tcp_random_rptr;
23474 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23475 		tcp_random_rptr = tcp_random_state;
23476 
23477 	mutex_exit(&tcp_random_lock);
23478 	return (i);
23479 }
23480 
23481 static int
23482 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23483     int *t_errorp, int *sys_errorp)
23484 {
23485 	int error;
23486 	int is_absreq_failure;
23487 	t_scalar_t *opt_lenp;
23488 	t_scalar_t opt_offset;
23489 	int prim_type;
23490 	struct T_conn_req *tcreqp;
23491 	struct T_conn_res *tcresp;
23492 	cred_t *cr;
23493 
23494 	/*
23495 	 * All Solaris components should pass a db_credp
23496 	 * for this TPI message, hence we ASSERT.
23497 	 * But in case there is some other M_PROTO that looks
23498 	 * like a TPI message sent by some other kernel
23499 	 * component, we check and return an error.
23500 	 */
23501 	cr = msg_getcred(mp, NULL);
23502 	ASSERT(cr != NULL);
23503 	if (cr == NULL)
23504 		return (-1);
23505 
23506 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23507 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23508 	    prim_type == T_CONN_RES);
23509 
23510 	switch (prim_type) {
23511 	case T_CONN_REQ:
23512 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23513 		opt_offset = tcreqp->OPT_offset;
23514 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23515 		break;
23516 	case O_T_CONN_RES:
23517 	case T_CONN_RES:
23518 		tcresp = (struct T_conn_res *)mp->b_rptr;
23519 		opt_offset = tcresp->OPT_offset;
23520 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23521 		break;
23522 	}
23523 
23524 	*t_errorp = 0;
23525 	*sys_errorp = 0;
23526 	*do_disconnectp = 0;
23527 
23528 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23529 	    opt_offset, cr, &tcp_opt_obj,
23530 	    NULL, &is_absreq_failure);
23531 
23532 	switch (error) {
23533 	case  0:		/* no error */
23534 		ASSERT(is_absreq_failure == 0);
23535 		return (0);
23536 	case ENOPROTOOPT:
23537 		*t_errorp = TBADOPT;
23538 		break;
23539 	case EACCES:
23540 		*t_errorp = TACCES;
23541 		break;
23542 	default:
23543 		*t_errorp = TSYSERR; *sys_errorp = error;
23544 		break;
23545 	}
23546 	if (is_absreq_failure != 0) {
23547 		/*
23548 		 * The connection request should get the local ack
23549 		 * T_OK_ACK and then a T_DISCON_IND.
23550 		 */
23551 		*do_disconnectp = 1;
23552 	}
23553 	return (-1);
23554 }
23555 
23556 /*
23557  * Split this function out so that if the secret changes, I'm okay.
23558  *
23559  * Initialize the tcp_iss_cookie and tcp_iss_key.
23560  */
23561 
23562 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23563 
23564 static void
23565 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
23566 {
23567 	struct {
23568 		int32_t current_time;
23569 		uint32_t randnum;
23570 		uint16_t pad;
23571 		uint8_t ether[6];
23572 		uint8_t passwd[PASSWD_SIZE];
23573 	} tcp_iss_cookie;
23574 	time_t t;
23575 
23576 	/*
23577 	 * Start with the current absolute time.
23578 	 */
23579 	(void) drv_getparm(TIME, &t);
23580 	tcp_iss_cookie.current_time = t;
23581 
23582 	/*
23583 	 * XXX - Need a more random number per RFC 1750, not this crap.
23584 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23585 	 */
23586 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23587 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23588 
23589 	/*
23590 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23591 	 * as a good template.
23592 	 */
23593 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23594 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23595 
23596 	/*
23597 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23598 	 */
23599 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23600 
23601 	/*
23602 	 * See 4010593 if this section becomes a problem again,
23603 	 * but the local ethernet address is useful here.
23604 	 */
23605 	(void) localetheraddr(NULL,
23606 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23607 
23608 	/*
23609 	 * Hash 'em all together.  The MD5Final is called per-connection.
23610 	 */
23611 	mutex_enter(&tcps->tcps_iss_key_lock);
23612 	MD5Init(&tcps->tcps_iss_key);
23613 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
23614 	    sizeof (tcp_iss_cookie));
23615 	mutex_exit(&tcps->tcps_iss_key_lock);
23616 }
23617 
23618 /*
23619  * Set the RFC 1948 pass phrase
23620  */
23621 /* ARGSUSED */
23622 static int
23623 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23624     cred_t *cr)
23625 {
23626 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23627 
23628 	/*
23629 	 * Basically, value contains a new pass phrase.  Pass it along!
23630 	 */
23631 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
23632 	return (0);
23633 }
23634 
23635 /* ARGSUSED */
23636 static int
23637 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23638 {
23639 	bzero(buf, sizeof (tcp_sack_info_t));
23640 	return (0);
23641 }
23642 
23643 /* ARGSUSED */
23644 static int
23645 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23646 {
23647 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23648 	return (0);
23649 }
23650 
23651 /*
23652  * Make sure we wait until the default queue is setup, yet allow
23653  * tcp_g_q_create() to open a TCP stream.
23654  * We need to allow tcp_g_q_create() do do an open
23655  * of tcp, hence we compare curhread.
23656  * All others have to wait until the tcps_g_q has been
23657  * setup.
23658  */
23659 void
23660 tcp_g_q_setup(tcp_stack_t *tcps)
23661 {
23662 	mutex_enter(&tcps->tcps_g_q_lock);
23663 	if (tcps->tcps_g_q != NULL) {
23664 		mutex_exit(&tcps->tcps_g_q_lock);
23665 		return;
23666 	}
23667 	if (tcps->tcps_g_q_creator == NULL) {
23668 		/* This thread will set it up */
23669 		tcps->tcps_g_q_creator = curthread;
23670 		mutex_exit(&tcps->tcps_g_q_lock);
23671 		tcp_g_q_create(tcps);
23672 		mutex_enter(&tcps->tcps_g_q_lock);
23673 		ASSERT(tcps->tcps_g_q_creator == curthread);
23674 		tcps->tcps_g_q_creator = NULL;
23675 		cv_signal(&tcps->tcps_g_q_cv);
23676 		ASSERT(tcps->tcps_g_q != NULL);
23677 		mutex_exit(&tcps->tcps_g_q_lock);
23678 		return;
23679 	}
23680 	/* Everybody but the creator has to wait */
23681 	if (tcps->tcps_g_q_creator != curthread) {
23682 		while (tcps->tcps_g_q == NULL)
23683 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
23684 	}
23685 	mutex_exit(&tcps->tcps_g_q_lock);
23686 }
23687 
23688 #define	IP	"ip"
23689 
23690 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
23691 
23692 /*
23693  * Create a default tcp queue here instead of in strplumb
23694  */
23695 void
23696 tcp_g_q_create(tcp_stack_t *tcps)
23697 {
23698 	int error;
23699 	ldi_handle_t	lh = NULL;
23700 	ldi_ident_t	li = NULL;
23701 	int		rval;
23702 	cred_t		*cr;
23703 	major_t IP_MAJ;
23704 
23705 #ifdef NS_DEBUG
23706 	(void) printf("tcp_g_q_create()\n");
23707 #endif
23708 
23709 	IP_MAJ = ddi_name_to_major(IP);
23710 
23711 	ASSERT(tcps->tcps_g_q_creator == curthread);
23712 
23713 	error = ldi_ident_from_major(IP_MAJ, &li);
23714 	if (error) {
23715 #ifdef DEBUG
23716 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
23717 		    error);
23718 #endif
23719 		return;
23720 	}
23721 
23722 	cr = zone_get_kcred(netstackid_to_zoneid(
23723 	    tcps->tcps_netstack->netstack_stackid));
23724 	ASSERT(cr != NULL);
23725 	/*
23726 	 * We set the tcp default queue to IPv6 because IPv4 falls
23727 	 * back to IPv6 when it can't find a client, but
23728 	 * IPv6 does not fall back to IPv4.
23729 	 */
23730 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
23731 	if (error) {
23732 #ifdef DEBUG
23733 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
23734 		    error);
23735 #endif
23736 		goto out;
23737 	}
23738 
23739 	/*
23740 	 * This ioctl causes the tcp framework to cache a pointer to
23741 	 * this stream, so we don't want to close the stream after
23742 	 * this operation.
23743 	 * Use the kernel credentials that are for the zone we're in.
23744 	 */
23745 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
23746 	    (intptr_t)0, FKIOCTL, cr, &rval);
23747 	if (error) {
23748 #ifdef DEBUG
23749 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
23750 		    "error %d\n", error);
23751 #endif
23752 		goto out;
23753 	}
23754 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
23755 	lh = NULL;
23756 out:
23757 	/* Close layered handles */
23758 	if (li)
23759 		ldi_ident_release(li);
23760 	/* Keep cred around until _inactive needs it */
23761 	tcps->tcps_g_q_cr = cr;
23762 }
23763 
23764 /*
23765  * We keep tcp_g_q set until all other tcp_t's in the zone
23766  * has gone away, and then when tcp_g_q_inactive() is called
23767  * we clear it.
23768  */
23769 void
23770 tcp_g_q_destroy(tcp_stack_t *tcps)
23771 {
23772 #ifdef NS_DEBUG
23773 	(void) printf("tcp_g_q_destroy()for stack %d\n",
23774 	    tcps->tcps_netstack->netstack_stackid);
23775 #endif
23776 
23777 	if (tcps->tcps_g_q == NULL) {
23778 		return;	/* Nothing to cleanup */
23779 	}
23780 	/*
23781 	 * Drop reference corresponding to the default queue.
23782 	 * This reference was added from tcp_open when the default queue
23783 	 * was created, hence we compensate for this extra drop in
23784 	 * tcp_g_q_close. If the refcnt drops to zero here it means
23785 	 * the default queue was the last one to be open, in which
23786 	 * case, then tcp_g_q_inactive will be
23787 	 * called as a result of the refrele.
23788 	 */
23789 	TCPS_REFRELE(tcps);
23790 }
23791 
23792 /*
23793  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23794  * Run by tcp_q_q_inactive using a taskq.
23795  */
23796 static void
23797 tcp_g_q_close(void *arg)
23798 {
23799 	tcp_stack_t *tcps = arg;
23800 	int error;
23801 	ldi_handle_t	lh = NULL;
23802 	ldi_ident_t	li = NULL;
23803 	cred_t		*cr;
23804 	major_t IP_MAJ;
23805 
23806 	IP_MAJ = ddi_name_to_major(IP);
23807 
23808 #ifdef NS_DEBUG
23809 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
23810 	    tcps->tcps_netstack->netstack_stackid,
23811 	    tcps->tcps_netstack->netstack_refcnt);
23812 #endif
23813 	lh = tcps->tcps_g_q_lh;
23814 	if (lh == NULL)
23815 		return;	/* Nothing to cleanup */
23816 
23817 	ASSERT(tcps->tcps_refcnt == 1);
23818 	ASSERT(tcps->tcps_g_q != NULL);
23819 
23820 	error = ldi_ident_from_major(IP_MAJ, &li);
23821 	if (error) {
23822 #ifdef DEBUG
23823 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
23824 		    error);
23825 #endif
23826 		return;
23827 	}
23828 
23829 	cr = tcps->tcps_g_q_cr;
23830 	tcps->tcps_g_q_cr = NULL;
23831 	ASSERT(cr != NULL);
23832 
23833 	/*
23834 	 * Make sure we can break the recursion when tcp_close decrements
23835 	 * the reference count causing g_q_inactive to be called again.
23836 	 */
23837 	tcps->tcps_g_q_lh = NULL;
23838 
23839 	/* close the default queue */
23840 	(void) ldi_close(lh, FREAD|FWRITE, cr);
23841 	/*
23842 	 * At this point in time tcps and the rest of netstack_t might
23843 	 * have been deleted.
23844 	 */
23845 	tcps = NULL;
23846 
23847 	/* Close layered handles */
23848 	ldi_ident_release(li);
23849 	crfree(cr);
23850 }
23851 
23852 /*
23853  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23854  *
23855  * Have to ensure that the ldi routines are not used by an
23856  * interrupt thread by using a taskq.
23857  */
23858 void
23859 tcp_g_q_inactive(tcp_stack_t *tcps)
23860 {
23861 	if (tcps->tcps_g_q_lh == NULL)
23862 		return;	/* Nothing to cleanup */
23863 
23864 	ASSERT(tcps->tcps_refcnt == 0);
23865 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
23866 
23867 	if (servicing_interrupt()) {
23868 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
23869 		    (void *) tcps, TQ_SLEEP);
23870 	} else {
23871 		tcp_g_q_close(tcps);
23872 	}
23873 }
23874 
23875 /*
23876  * Called by IP when IP is loaded into the kernel
23877  */
23878 void
23879 tcp_ddi_g_init(void)
23880 {
23881 	tcp_timercache = kmem_cache_create("tcp_timercache",
23882 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23883 	    NULL, NULL, NULL, NULL, NULL, 0);
23884 
23885 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23886 	    sizeof (tcp_sack_info_t), 0,
23887 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23888 
23889 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23890 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23891 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23892 
23893 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23894 
23895 	/* Initialize the random number generator */
23896 	tcp_random_init();
23897 
23898 	/* A single callback independently of how many netstacks we have */
23899 	ip_squeue_init(tcp_squeue_add);
23900 
23901 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
23902 
23903 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
23904 	    TASKQ_PREPOPULATE);
23905 
23906 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
23907 
23908 	/*
23909 	 * We want to be informed each time a stack is created or
23910 	 * destroyed in the kernel, so we can maintain the
23911 	 * set of tcp_stack_t's.
23912 	 */
23913 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
23914 	    tcp_stack_fini);
23915 }
23916 
23917 
23918 #define	INET_NAME	"ip"
23919 
23920 /*
23921  * Initialize the TCP stack instance.
23922  */
23923 static void *
23924 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
23925 {
23926 	tcp_stack_t	*tcps;
23927 	tcpparam_t	*pa;
23928 	int		i;
23929 	int		error = 0;
23930 	major_t		major;
23931 
23932 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
23933 	tcps->tcps_netstack = ns;
23934 
23935 	/* Initialize locks */
23936 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23937 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
23938 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23939 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23940 
23941 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
23942 	tcps->tcps_g_epriv_ports[0] = 2049;
23943 	tcps->tcps_g_epriv_ports[1] = 4045;
23944 	tcps->tcps_min_anonpriv_port = 512;
23945 
23946 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
23947 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
23948 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
23949 	    TCP_FANOUT_SIZE, KM_SLEEP);
23950 
23951 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
23952 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
23953 		    MUTEX_DEFAULT, NULL);
23954 	}
23955 
23956 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
23957 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
23958 		    MUTEX_DEFAULT, NULL);
23959 	}
23960 
23961 	/* TCP's IPsec code calls the packet dropper. */
23962 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
23963 
23964 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
23965 	tcps->tcps_params = pa;
23966 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
23967 
23968 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
23969 	    A_CNT(lcl_tcp_param_arr), tcps);
23970 
23971 	/*
23972 	 * Note: To really walk the device tree you need the devinfo
23973 	 * pointer to your device which is only available after probe/attach.
23974 	 * The following is safe only because it uses ddi_root_node()
23975 	 */
23976 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23977 	    tcp_opt_obj.odb_opt_arr_cnt);
23978 
23979 	/*
23980 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23981 	 * by the boot scripts.
23982 	 *
23983 	 * Use NULL name, as the name is caught by the new lockstats.
23984 	 *
23985 	 * Initialize with some random, non-guessable string, like the global
23986 	 * T_INFO_ACK.
23987 	 */
23988 
23989 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23990 	    sizeof (tcp_g_t_info_ack), tcps);
23991 
23992 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
23993 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
23994 
23995 	major = mod_name_to_major(INET_NAME);
23996 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
23997 	ASSERT(error == 0);
23998 	return (tcps);
23999 }
24000 
24001 /*
24002  * Called when the IP module is about to be unloaded.
24003  */
24004 void
24005 tcp_ddi_g_destroy(void)
24006 {
24007 	tcp_g_kstat_fini(tcp_g_kstat);
24008 	tcp_g_kstat = NULL;
24009 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24010 
24011 	mutex_destroy(&tcp_random_lock);
24012 
24013 	kmem_cache_destroy(tcp_timercache);
24014 	kmem_cache_destroy(tcp_sack_info_cache);
24015 	kmem_cache_destroy(tcp_iphc_cache);
24016 
24017 	netstack_unregister(NS_TCP);
24018 	taskq_destroy(tcp_taskq);
24019 }
24020 
24021 /*
24022  * Shut down the TCP stack instance.
24023  */
24024 /* ARGSUSED */
24025 static void
24026 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24027 {
24028 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24029 
24030 	tcp_g_q_destroy(tcps);
24031 }
24032 
24033 /*
24034  * Free the TCP stack instance.
24035  */
24036 static void
24037 tcp_stack_fini(netstackid_t stackid, void *arg)
24038 {
24039 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24040 	int i;
24041 
24042 	nd_free(&tcps->tcps_g_nd);
24043 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24044 	tcps->tcps_params = NULL;
24045 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24046 	tcps->tcps_wroff_xtra_param = NULL;
24047 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24048 	tcps->tcps_mdt_head_param = NULL;
24049 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24050 	tcps->tcps_mdt_tail_param = NULL;
24051 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24052 	tcps->tcps_mdt_max_pbufs_param = NULL;
24053 
24054 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24055 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24056 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24057 	}
24058 
24059 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24060 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24061 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24062 	}
24063 
24064 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24065 	tcps->tcps_bind_fanout = NULL;
24066 
24067 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24068 	tcps->tcps_acceptor_fanout = NULL;
24069 
24070 	mutex_destroy(&tcps->tcps_iss_key_lock);
24071 	mutex_destroy(&tcps->tcps_g_q_lock);
24072 	cv_destroy(&tcps->tcps_g_q_cv);
24073 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24074 
24075 	ip_drop_unregister(&tcps->tcps_dropper);
24076 
24077 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24078 	tcps->tcps_kstat = NULL;
24079 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24080 
24081 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24082 	tcps->tcps_mibkp = NULL;
24083 
24084 	ldi_ident_release(tcps->tcps_ldi_ident);
24085 	kmem_free(tcps, sizeof (*tcps));
24086 }
24087 
24088 /*
24089  * Generate ISS, taking into account NDD changes may happen halfway through.
24090  * (If the iss is not zero, set it.)
24091  */
24092 
24093 static void
24094 tcp_iss_init(tcp_t *tcp)
24095 {
24096 	MD5_CTX context;
24097 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24098 	uint32_t answer[4];
24099 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24100 
24101 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24102 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24103 	switch (tcps->tcps_strong_iss) {
24104 	case 2:
24105 		mutex_enter(&tcps->tcps_iss_key_lock);
24106 		context = tcps->tcps_iss_key;
24107 		mutex_exit(&tcps->tcps_iss_key_lock);
24108 		arg.ports = tcp->tcp_ports;
24109 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24110 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24111 			    &arg.src);
24112 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24113 			    &arg.dst);
24114 		} else {
24115 			arg.src = tcp->tcp_ip6h->ip6_src;
24116 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24117 		}
24118 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24119 		MD5Final((uchar_t *)answer, &context);
24120 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24121 		/*
24122 		 * Now that we've hashed into a unique per-connection sequence
24123 		 * space, add a random increment per strong_iss == 1.  So I
24124 		 * guess we'll have to...
24125 		 */
24126 		/* FALLTHRU */
24127 	case 1:
24128 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24129 		break;
24130 	default:
24131 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24132 		break;
24133 	}
24134 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24135 	tcp->tcp_fss = tcp->tcp_iss - 1;
24136 	tcp->tcp_suna = tcp->tcp_iss;
24137 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24138 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24139 	tcp->tcp_csuna = tcp->tcp_snxt;
24140 }
24141 
24142 /*
24143  * Exported routine for extracting active tcp connection status.
24144  *
24145  * This is used by the Solaris Cluster Networking software to
24146  * gather a list of connections that need to be forwarded to
24147  * specific nodes in the cluster when configuration changes occur.
24148  *
24149  * The callback is invoked for each tcp_t structure from all netstacks,
24150  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24151  * from the netstack with the specified stack_id. Returning
24152  * non-zero from the callback routine terminates the search.
24153  */
24154 int
24155 cl_tcp_walk_list(netstackid_t stack_id,
24156     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24157 {
24158 	netstack_handle_t nh;
24159 	netstack_t *ns;
24160 	int ret = 0;
24161 
24162 	if (stack_id >= 0) {
24163 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24164 			return (EINVAL);
24165 
24166 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24167 		    ns->netstack_tcp);
24168 		netstack_rele(ns);
24169 		return (ret);
24170 	}
24171 
24172 	netstack_next_init(&nh);
24173 	while ((ns = netstack_next(&nh)) != NULL) {
24174 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24175 		    ns->netstack_tcp);
24176 		netstack_rele(ns);
24177 	}
24178 	netstack_next_fini(&nh);
24179 	return (ret);
24180 }
24181 
24182 static int
24183 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
24184     tcp_stack_t *tcps)
24185 {
24186 	tcp_t *tcp;
24187 	cl_tcp_info_t	cl_tcpi;
24188 	connf_t	*connfp;
24189 	conn_t	*connp;
24190 	int	i;
24191 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24192 
24193 	ASSERT(callback != NULL);
24194 
24195 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24196 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
24197 		connp = NULL;
24198 
24199 		while ((connp =
24200 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24201 
24202 			tcp = connp->conn_tcp;
24203 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24204 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24205 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24206 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24207 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24208 			/*
24209 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24210 			 * addresses. They are copied implicitly below as
24211 			 * mapped addresses.
24212 			 */
24213 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24214 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24215 				cl_tcpi.cl_tcpi_faddr =
24216 				    tcp->tcp_ipha->ipha_dst;
24217 			} else {
24218 				cl_tcpi.cl_tcpi_faddr_v6 =
24219 				    tcp->tcp_ip6h->ip6_dst;
24220 			}
24221 
24222 			/*
24223 			 * If the callback returns non-zero
24224 			 * we terminate the traversal.
24225 			 */
24226 			if ((*callback)(&cl_tcpi, arg) != 0) {
24227 				CONN_DEC_REF(tcp->tcp_connp);
24228 				return (1);
24229 			}
24230 		}
24231 	}
24232 
24233 	return (0);
24234 }
24235 
24236 /*
24237  * Macros used for accessing the different types of sockaddr
24238  * structures inside a tcp_ioc_abort_conn_t.
24239  */
24240 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24241 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24242 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24243 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24244 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24245 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24246 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24247 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24248 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24249 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24250 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24251 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24252 
24253 /*
24254  * Return the correct error code to mimic the behavior
24255  * of a connection reset.
24256  */
24257 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24258 		switch ((state)) {		\
24259 		case TCPS_SYN_SENT:		\
24260 		case TCPS_SYN_RCVD:		\
24261 			(err) = ECONNREFUSED;	\
24262 			break;			\
24263 		case TCPS_ESTABLISHED:		\
24264 		case TCPS_FIN_WAIT_1:		\
24265 		case TCPS_FIN_WAIT_2:		\
24266 		case TCPS_CLOSE_WAIT:		\
24267 			(err) = ECONNRESET;	\
24268 			break;			\
24269 		case TCPS_CLOSING:		\
24270 		case TCPS_LAST_ACK:		\
24271 		case TCPS_TIME_WAIT:		\
24272 			(err) = 0;		\
24273 			break;			\
24274 		default:			\
24275 			(err) = ENXIO;		\
24276 		}				\
24277 	}
24278 
24279 /*
24280  * Check if a tcp structure matches the info in acp.
24281  */
24282 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24283 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24284 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24285 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24286 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24287 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24288 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24289 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24290 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24291 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24292 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24293 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24294 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24295 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24296 	&(tcp)->tcp_ip_src_v6)) &&				\
24297 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24298 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24299 	&(tcp)->tcp_remote_v6)) &&				\
24300 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24301 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24302 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24303 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24304 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24305 	(acp)->ac_end >= (tcp)->tcp_state))
24306 
24307 #define	TCP_AC_MATCH(acp, tcp)					\
24308 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24309 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24310 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24311 
24312 /*
24313  * Build a message containing a tcp_ioc_abort_conn_t structure
24314  * which is filled in with information from acp and tp.
24315  */
24316 static mblk_t *
24317 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24318 {
24319 	mblk_t *mp;
24320 	tcp_ioc_abort_conn_t *tacp;
24321 
24322 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24323 	if (mp == NULL)
24324 		return (NULL);
24325 
24326 	mp->b_datap->db_type = M_CTL;
24327 
24328 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24329 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24330 	    sizeof (uint32_t));
24331 
24332 	tacp->ac_start = acp->ac_start;
24333 	tacp->ac_end = acp->ac_end;
24334 	tacp->ac_zoneid = acp->ac_zoneid;
24335 
24336 	if (acp->ac_local.ss_family == AF_INET) {
24337 		tacp->ac_local.ss_family = AF_INET;
24338 		tacp->ac_remote.ss_family = AF_INET;
24339 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24340 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24341 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24342 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24343 	} else {
24344 		tacp->ac_local.ss_family = AF_INET6;
24345 		tacp->ac_remote.ss_family = AF_INET6;
24346 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24347 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24348 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24349 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24350 	}
24351 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24352 	return (mp);
24353 }
24354 
24355 /*
24356  * Print a tcp_ioc_abort_conn_t structure.
24357  */
24358 static void
24359 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24360 {
24361 	char lbuf[128];
24362 	char rbuf[128];
24363 	sa_family_t af;
24364 	in_port_t lport, rport;
24365 	ushort_t logflags;
24366 
24367 	af = acp->ac_local.ss_family;
24368 
24369 	if (af == AF_INET) {
24370 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24371 		    lbuf, 128);
24372 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24373 		    rbuf, 128);
24374 		lport = ntohs(TCP_AC_V4LPORT(acp));
24375 		rport = ntohs(TCP_AC_V4RPORT(acp));
24376 	} else {
24377 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24378 		    lbuf, 128);
24379 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24380 		    rbuf, 128);
24381 		lport = ntohs(TCP_AC_V6LPORT(acp));
24382 		rport = ntohs(TCP_AC_V6RPORT(acp));
24383 	}
24384 
24385 	logflags = SL_TRACE | SL_NOTE;
24386 	/*
24387 	 * Don't print this message to the console if the operation was done
24388 	 * to a non-global zone.
24389 	 */
24390 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24391 		logflags |= SL_CONSOLE;
24392 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24393 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24394 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24395 	    acp->ac_start, acp->ac_end);
24396 }
24397 
24398 /*
24399  * Called inside tcp_rput when a message built using
24400  * tcp_ioctl_abort_build_msg is put into a queue.
24401  * Note that when we get here there is no wildcard in acp any more.
24402  */
24403 static void
24404 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24405 {
24406 	tcp_ioc_abort_conn_t *acp;
24407 
24408 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24409 	if (tcp->tcp_state <= acp->ac_end) {
24410 		/*
24411 		 * If we get here, we are already on the correct
24412 		 * squeue. This ioctl follows the following path
24413 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24414 		 * ->tcp_ioctl_abort->squeue_enter (if on a
24415 		 * different squeue)
24416 		 */
24417 		int errcode;
24418 
24419 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24420 		(void) tcp_clean_death(tcp, errcode, 26);
24421 	}
24422 	freemsg(mp);
24423 }
24424 
24425 /*
24426  * Abort all matching connections on a hash chain.
24427  */
24428 static int
24429 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24430     boolean_t exact, tcp_stack_t *tcps)
24431 {
24432 	int nmatch, err = 0;
24433 	tcp_t *tcp;
24434 	MBLKP mp, last, listhead = NULL;
24435 	conn_t	*tconnp;
24436 	connf_t	*connfp;
24437 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24438 
24439 	connfp = &ipst->ips_ipcl_conn_fanout[index];
24440 
24441 startover:
24442 	nmatch = 0;
24443 
24444 	mutex_enter(&connfp->connf_lock);
24445 	for (tconnp = connfp->connf_head; tconnp != NULL;
24446 	    tconnp = tconnp->conn_next) {
24447 		tcp = tconnp->conn_tcp;
24448 		if (TCP_AC_MATCH(acp, tcp)) {
24449 			CONN_INC_REF(tcp->tcp_connp);
24450 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24451 			if (mp == NULL) {
24452 				err = ENOMEM;
24453 				CONN_DEC_REF(tcp->tcp_connp);
24454 				break;
24455 			}
24456 			mp->b_prev = (mblk_t *)tcp;
24457 
24458 			if (listhead == NULL) {
24459 				listhead = mp;
24460 				last = mp;
24461 			} else {
24462 				last->b_next = mp;
24463 				last = mp;
24464 			}
24465 			nmatch++;
24466 			if (exact)
24467 				break;
24468 		}
24469 
24470 		/* Avoid holding lock for too long. */
24471 		if (nmatch >= 500)
24472 			break;
24473 	}
24474 	mutex_exit(&connfp->connf_lock);
24475 
24476 	/* Pass mp into the correct tcp */
24477 	while ((mp = listhead) != NULL) {
24478 		listhead = listhead->b_next;
24479 		tcp = (tcp_t *)mp->b_prev;
24480 		mp->b_next = mp->b_prev = NULL;
24481 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
24482 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
24483 	}
24484 
24485 	*count += nmatch;
24486 	if (nmatch >= 500 && err == 0)
24487 		goto startover;
24488 	return (err);
24489 }
24490 
24491 /*
24492  * Abort all connections that matches the attributes specified in acp.
24493  */
24494 static int
24495 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
24496 {
24497 	sa_family_t af;
24498 	uint32_t  ports;
24499 	uint16_t *pports;
24500 	int err = 0, count = 0;
24501 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24502 	int index = -1;
24503 	ushort_t logflags;
24504 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24505 
24506 	af = acp->ac_local.ss_family;
24507 
24508 	if (af == AF_INET) {
24509 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24510 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24511 			pports = (uint16_t *)&ports;
24512 			pports[1] = TCP_AC_V4LPORT(acp);
24513 			pports[0] = TCP_AC_V4RPORT(acp);
24514 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24515 		}
24516 	} else {
24517 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24518 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24519 			pports = (uint16_t *)&ports;
24520 			pports[1] = TCP_AC_V6LPORT(acp);
24521 			pports[0] = TCP_AC_V6RPORT(acp);
24522 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24523 		}
24524 	}
24525 
24526 	/*
24527 	 * For cases where remote addr, local port, and remote port are non-
24528 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24529 	 */
24530 	if (index != -1) {
24531 		err = tcp_ioctl_abort_bucket(acp, index,
24532 		    &count, exact, tcps);
24533 	} else {
24534 		/*
24535 		 * loop through all entries for wildcard case
24536 		 */
24537 		for (index = 0;
24538 		    index < ipst->ips_ipcl_conn_fanout_size;
24539 		    index++) {
24540 			err = tcp_ioctl_abort_bucket(acp, index,
24541 			    &count, exact, tcps);
24542 			if (err != 0)
24543 				break;
24544 		}
24545 	}
24546 
24547 	logflags = SL_TRACE | SL_NOTE;
24548 	/*
24549 	 * Don't print this message to the console if the operation was done
24550 	 * to a non-global zone.
24551 	 */
24552 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24553 		logflags |= SL_CONSOLE;
24554 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24555 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24556 	if (err == 0 && count == 0)
24557 		err = ENOENT;
24558 	return (err);
24559 }
24560 
24561 /*
24562  * Process the TCP_IOC_ABORT_CONN ioctl request.
24563  */
24564 static void
24565 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24566 {
24567 	int	err;
24568 	IOCP    iocp;
24569 	MBLKP   mp1;
24570 	sa_family_t laf, raf;
24571 	tcp_ioc_abort_conn_t *acp;
24572 	zone_t		*zptr;
24573 	conn_t		*connp = Q_TO_CONN(q);
24574 	zoneid_t	zoneid = connp->conn_zoneid;
24575 	tcp_t		*tcp = connp->conn_tcp;
24576 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24577 
24578 	iocp = (IOCP)mp->b_rptr;
24579 
24580 	if ((mp1 = mp->b_cont) == NULL ||
24581 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24582 		err = EINVAL;
24583 		goto out;
24584 	}
24585 
24586 	/* check permissions */
24587 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
24588 		err = EPERM;
24589 		goto out;
24590 	}
24591 
24592 	if (mp1->b_cont != NULL) {
24593 		freemsg(mp1->b_cont);
24594 		mp1->b_cont = NULL;
24595 	}
24596 
24597 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24598 	laf = acp->ac_local.ss_family;
24599 	raf = acp->ac_remote.ss_family;
24600 
24601 	/* check that a zone with the supplied zoneid exists */
24602 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24603 		zptr = zone_find_by_id(zoneid);
24604 		if (zptr != NULL) {
24605 			zone_rele(zptr);
24606 		} else {
24607 			err = EINVAL;
24608 			goto out;
24609 		}
24610 	}
24611 
24612 	/*
24613 	 * For exclusive stacks we set the zoneid to zero
24614 	 * to make TCP operate as if in the global zone.
24615 	 */
24616 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
24617 		acp->ac_zoneid = GLOBAL_ZONEID;
24618 
24619 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24620 	    acp->ac_start > acp->ac_end || laf != raf ||
24621 	    (laf != AF_INET && laf != AF_INET6)) {
24622 		err = EINVAL;
24623 		goto out;
24624 	}
24625 
24626 	tcp_ioctl_abort_dump(acp);
24627 	err = tcp_ioctl_abort(acp, tcps);
24628 
24629 out:
24630 	if (mp1 != NULL) {
24631 		freemsg(mp1);
24632 		mp->b_cont = NULL;
24633 	}
24634 
24635 	if (err != 0)
24636 		miocnak(q, mp, 0, err);
24637 	else
24638 		miocack(q, mp, 0, 0);
24639 }
24640 
24641 /*
24642  * tcp_time_wait_processing() handles processing of incoming packets when
24643  * the tcp is in the TIME_WAIT state.
24644  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24645  * on the time wait list.
24646  */
24647 void
24648 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24649     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24650 {
24651 	int32_t		bytes_acked;
24652 	int32_t		gap;
24653 	int32_t		rgap;
24654 	tcp_opt_t	tcpopt;
24655 	uint_t		flags;
24656 	uint32_t	new_swnd = 0;
24657 	conn_t		*connp;
24658 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24659 
24660 	BUMP_LOCAL(tcp->tcp_ibsegs);
24661 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
24662 
24663 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24664 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24665 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24666 	if (tcp->tcp_snd_ts_ok) {
24667 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24668 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24669 			    tcp->tcp_rnxt, TH_ACK);
24670 			goto done;
24671 		}
24672 	}
24673 	gap = seg_seq - tcp->tcp_rnxt;
24674 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24675 	if (gap < 0) {
24676 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
24677 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
24678 		    (seg_len > -gap ? -gap : seg_len));
24679 		seg_len += gap;
24680 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24681 			if (flags & TH_RST) {
24682 				goto done;
24683 			}
24684 			if ((flags & TH_FIN) && seg_len == -1) {
24685 				/*
24686 				 * When TCP receives a duplicate FIN in
24687 				 * TIME_WAIT state, restart the 2 MSL timer.
24688 				 * See page 73 in RFC 793. Make sure this TCP
24689 				 * is already on the TIME_WAIT list. If not,
24690 				 * just restart the timer.
24691 				 */
24692 				if (TCP_IS_DETACHED(tcp)) {
24693 					if (tcp_time_wait_remove(tcp, NULL) ==
24694 					    B_TRUE) {
24695 						tcp_time_wait_append(tcp);
24696 						TCP_DBGSTAT(tcps,
24697 						    tcp_rput_time_wait);
24698 					}
24699 				} else {
24700 					ASSERT(tcp != NULL);
24701 					TCP_TIMER_RESTART(tcp,
24702 					    tcps->tcps_time_wait_interval);
24703 				}
24704 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24705 				    tcp->tcp_rnxt, TH_ACK);
24706 				goto done;
24707 			}
24708 			flags |=  TH_ACK_NEEDED;
24709 			seg_len = 0;
24710 			goto process_ack;
24711 		}
24712 
24713 		/* Fix seg_seq, and chew the gap off the front. */
24714 		seg_seq = tcp->tcp_rnxt;
24715 	}
24716 
24717 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24718 		/*
24719 		 * Make sure that when we accept the connection, pick
24720 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24721 		 * old connection.
24722 		 *
24723 		 * The next ISS generated is equal to tcp_iss_incr_extra
24724 		 * + ISS_INCR/2 + other components depending on the
24725 		 * value of tcp_strong_iss.  We pre-calculate the new
24726 		 * ISS here and compare with tcp_snxt to determine if
24727 		 * we need to make adjustment to tcp_iss_incr_extra.
24728 		 *
24729 		 * The above calculation is ugly and is a
24730 		 * waste of CPU cycles...
24731 		 */
24732 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
24733 		int32_t adj;
24734 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24735 
24736 		switch (tcps->tcps_strong_iss) {
24737 		case 2: {
24738 			/* Add time and MD5 components. */
24739 			uint32_t answer[4];
24740 			struct {
24741 				uint32_t ports;
24742 				in6_addr_t src;
24743 				in6_addr_t dst;
24744 			} arg;
24745 			MD5_CTX context;
24746 
24747 			mutex_enter(&tcps->tcps_iss_key_lock);
24748 			context = tcps->tcps_iss_key;
24749 			mutex_exit(&tcps->tcps_iss_key_lock);
24750 			arg.ports = tcp->tcp_ports;
24751 			/* We use MAPPED addresses in tcp_iss_init */
24752 			arg.src = tcp->tcp_ip_src_v6;
24753 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24754 				IN6_IPADDR_TO_V4MAPPED(
24755 				    tcp->tcp_ipha->ipha_dst,
24756 				    &arg.dst);
24757 			} else {
24758 				arg.dst =
24759 				    tcp->tcp_ip6h->ip6_dst;
24760 			}
24761 			MD5Update(&context, (uchar_t *)&arg,
24762 			    sizeof (arg));
24763 			MD5Final((uchar_t *)answer, &context);
24764 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24765 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24766 			break;
24767 		}
24768 		case 1:
24769 			/* Add time component and min random (i.e. 1). */
24770 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24771 			break;
24772 		default:
24773 			/* Add only time component. */
24774 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24775 			break;
24776 		}
24777 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24778 			/*
24779 			 * New ISS not guaranteed to be ISS_INCR/2
24780 			 * ahead of the current tcp_snxt, so add the
24781 			 * difference to tcp_iss_incr_extra.
24782 			 */
24783 			tcps->tcps_iss_incr_extra += adj;
24784 		}
24785 		/*
24786 		 * If tcp_clean_death() can not perform the task now,
24787 		 * drop the SYN packet and let the other side re-xmit.
24788 		 * Otherwise pass the SYN packet back in, since the
24789 		 * old tcp state has been cleaned up or freed.
24790 		 */
24791 		if (tcp_clean_death(tcp, 0, 27) == -1)
24792 			goto done;
24793 		/*
24794 		 * We will come back to tcp_rput_data
24795 		 * on the global queue. Packets destined
24796 		 * for the global queue will be checked
24797 		 * with global policy. But the policy for
24798 		 * this packet has already been checked as
24799 		 * this was destined for the detached
24800 		 * connection. We need to bypass policy
24801 		 * check this time by attaching a dummy
24802 		 * ipsec_in with ipsec_in_dont_check set.
24803 		 */
24804 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
24805 		if (connp != NULL) {
24806 			TCP_STAT(tcps, tcp_time_wait_syn_success);
24807 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24808 			return;
24809 		}
24810 		goto done;
24811 	}
24812 
24813 	/*
24814 	 * rgap is the amount of stuff received out of window.  A negative
24815 	 * value is the amount out of window.
24816 	 */
24817 	if (rgap < 0) {
24818 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
24819 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
24820 		/* Fix seg_len and make sure there is something left. */
24821 		seg_len += rgap;
24822 		if (seg_len <= 0) {
24823 			if (flags & TH_RST) {
24824 				goto done;
24825 			}
24826 			flags |=  TH_ACK_NEEDED;
24827 			seg_len = 0;
24828 			goto process_ack;
24829 		}
24830 	}
24831 	/*
24832 	 * Check whether we can update tcp_ts_recent.  This test is
24833 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24834 	 * Extensions for High Performance: An Update", Internet Draft.
24835 	 */
24836 	if (tcp->tcp_snd_ts_ok &&
24837 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24838 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24839 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24840 		tcp->tcp_last_rcv_lbolt = lbolt64;
24841 	}
24842 
24843 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24844 		/* Always ack out of order packets */
24845 		flags |= TH_ACK_NEEDED;
24846 		seg_len = 0;
24847 	} else if (seg_len > 0) {
24848 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
24849 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
24850 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
24851 	}
24852 	if (flags & TH_RST) {
24853 		(void) tcp_clean_death(tcp, 0, 28);
24854 		goto done;
24855 	}
24856 	if (flags & TH_SYN) {
24857 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24858 		    TH_RST|TH_ACK);
24859 		/*
24860 		 * Do not delete the TCP structure if it is in
24861 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24862 		 */
24863 		goto done;
24864 	}
24865 process_ack:
24866 	if (flags & TH_ACK) {
24867 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24868 		if (bytes_acked <= 0) {
24869 			if (bytes_acked == 0 && seg_len == 0 &&
24870 			    new_swnd == tcp->tcp_swnd)
24871 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
24872 		} else {
24873 			/* Acks something not sent */
24874 			flags |= TH_ACK_NEEDED;
24875 		}
24876 	}
24877 	if (flags & TH_ACK_NEEDED) {
24878 		/*
24879 		 * Time to send an ack for some reason.
24880 		 */
24881 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24882 		    tcp->tcp_rnxt, TH_ACK);
24883 	}
24884 done:
24885 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24886 		DB_CKSUMSTART(mp) = 0;
24887 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24888 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
24889 	}
24890 	freemsg(mp);
24891 }
24892 
24893 /*
24894  * TCP Timers Implementation.
24895  */
24896 timeout_id_t
24897 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24898 {
24899 	mblk_t *mp;
24900 	tcp_timer_t *tcpt;
24901 	tcp_t *tcp = connp->conn_tcp;
24902 
24903 	ASSERT(connp->conn_sqp != NULL);
24904 
24905 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
24906 
24907 	if (tcp->tcp_timercache == NULL) {
24908 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24909 	} else {
24910 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
24911 		mp = tcp->tcp_timercache;
24912 		tcp->tcp_timercache = mp->b_next;
24913 		mp->b_next = NULL;
24914 		ASSERT(mp->b_wptr == NULL);
24915 	}
24916 
24917 	CONN_INC_REF(connp);
24918 	tcpt = (tcp_timer_t *)mp->b_rptr;
24919 	tcpt->connp = connp;
24920 	tcpt->tcpt_proc = f;
24921 	/*
24922 	 * TCP timers are normal timeouts. Plus, they do not require more than
24923 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
24924 	 * rounding up the expiration to the next resolution boundary, we can
24925 	 * batch timers in the callout subsystem to make TCP timers more
24926 	 * efficient. The roundup also protects short timers from expiring too
24927 	 * early before they have a chance to be cancelled.
24928 	 */
24929 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
24930 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
24931 
24932 	return ((timeout_id_t)mp);
24933 }
24934 
24935 static void
24936 tcp_timer_callback(void *arg)
24937 {
24938 	mblk_t *mp = (mblk_t *)arg;
24939 	tcp_timer_t *tcpt;
24940 	conn_t	*connp;
24941 
24942 	tcpt = (tcp_timer_t *)mp->b_rptr;
24943 	connp = tcpt->connp;
24944 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
24945 	    SQ_FILL, SQTAG_TCP_TIMER);
24946 }
24947 
24948 static void
24949 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24950 {
24951 	tcp_timer_t *tcpt;
24952 	conn_t *connp = (conn_t *)arg;
24953 	tcp_t *tcp = connp->conn_tcp;
24954 
24955 	tcpt = (tcp_timer_t *)mp->b_rptr;
24956 	ASSERT(connp == tcpt->connp);
24957 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24958 
24959 	/*
24960 	 * If the TCP has reached the closed state, don't proceed any
24961 	 * further. This TCP logically does not exist on the system.
24962 	 * tcpt_proc could for example access queues, that have already
24963 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24964 	 */
24965 	if (tcp->tcp_state != TCPS_CLOSED) {
24966 		(*tcpt->tcpt_proc)(connp);
24967 	} else {
24968 		tcp->tcp_timer_tid = 0;
24969 	}
24970 	tcp_timer_free(connp->conn_tcp, mp);
24971 }
24972 
24973 /*
24974  * There is potential race with untimeout and the handler firing at the same
24975  * time. The mblock may be freed by the handler while we are trying to use
24976  * it. But since both should execute on the same squeue, this race should not
24977  * occur.
24978  */
24979 clock_t
24980 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24981 {
24982 	mblk_t	*mp = (mblk_t *)id;
24983 	tcp_timer_t *tcpt;
24984 	clock_t delta;
24985 
24986 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
24987 
24988 	if (mp == NULL)
24989 		return (-1);
24990 
24991 	tcpt = (tcp_timer_t *)mp->b_rptr;
24992 	ASSERT(tcpt->connp == connp);
24993 
24994 	delta = untimeout_default(tcpt->tcpt_tid, 0);
24995 
24996 	if (delta >= 0) {
24997 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
24998 		tcp_timer_free(connp->conn_tcp, mp);
24999 		CONN_DEC_REF(connp);
25000 	}
25001 
25002 	return (delta);
25003 }
25004 
25005 /*
25006  * Allocate space for the timer event. The allocation looks like mblk, but it is
25007  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25008  *
25009  * Dealing with failures: If we can't allocate from the timer cache we try
25010  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25011  * points to b_rptr.
25012  * If we can't allocate anything using allocb_tryhard(), we perform a last
25013  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25014  * save the actual allocation size in b_datap.
25015  */
25016 mblk_t *
25017 tcp_timermp_alloc(int kmflags)
25018 {
25019 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25020 	    kmflags & ~KM_PANIC);
25021 
25022 	if (mp != NULL) {
25023 		mp->b_next = mp->b_prev = NULL;
25024 		mp->b_rptr = (uchar_t *)(&mp[1]);
25025 		mp->b_wptr = NULL;
25026 		mp->b_datap = NULL;
25027 		mp->b_queue = NULL;
25028 		mp->b_cont = NULL;
25029 	} else if (kmflags & KM_PANIC) {
25030 		/*
25031 		 * Failed to allocate memory for the timer. Try allocating from
25032 		 * dblock caches.
25033 		 */
25034 		/* ipclassifier calls this from a constructor - hence no tcps */
25035 		TCP_G_STAT(tcp_timermp_allocfail);
25036 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25037 		if (mp == NULL) {
25038 			size_t size = 0;
25039 			/*
25040 			 * Memory is really low. Try tryhard allocation.
25041 			 *
25042 			 * ipclassifier calls this from a constructor -
25043 			 * hence no tcps
25044 			 */
25045 			TCP_G_STAT(tcp_timermp_allocdblfail);
25046 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25047 			    sizeof (tcp_timer_t), &size, kmflags);
25048 			mp->b_rptr = (uchar_t *)(&mp[1]);
25049 			mp->b_next = mp->b_prev = NULL;
25050 			mp->b_wptr = (uchar_t *)-1;
25051 			mp->b_datap = (dblk_t *)size;
25052 			mp->b_queue = NULL;
25053 			mp->b_cont = NULL;
25054 		}
25055 		ASSERT(mp->b_wptr != NULL);
25056 	}
25057 	/* ipclassifier calls this from a constructor - hence no tcps */
25058 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25059 
25060 	return (mp);
25061 }
25062 
25063 /*
25064  * Free per-tcp timer cache.
25065  * It can only contain entries from tcp_timercache.
25066  */
25067 void
25068 tcp_timermp_free(tcp_t *tcp)
25069 {
25070 	mblk_t *mp;
25071 
25072 	while ((mp = tcp->tcp_timercache) != NULL) {
25073 		ASSERT(mp->b_wptr == NULL);
25074 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25075 		kmem_cache_free(tcp_timercache, mp);
25076 	}
25077 }
25078 
25079 /*
25080  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25081  * events there already (currently at most two events are cached).
25082  * If the event is not allocated from the timer cache, free it right away.
25083  */
25084 static void
25085 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25086 {
25087 	mblk_t *mp1 = tcp->tcp_timercache;
25088 
25089 	if (mp->b_wptr != NULL) {
25090 		/*
25091 		 * This allocation is not from a timer cache, free it right
25092 		 * away.
25093 		 */
25094 		if (mp->b_wptr != (uchar_t *)-1)
25095 			freeb(mp);
25096 		else
25097 			kmem_free(mp, (size_t)mp->b_datap);
25098 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25099 		/* Cache this timer block for future allocations */
25100 		mp->b_rptr = (uchar_t *)(&mp[1]);
25101 		mp->b_next = mp1;
25102 		tcp->tcp_timercache = mp;
25103 	} else {
25104 		kmem_cache_free(tcp_timercache, mp);
25105 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25106 	}
25107 }
25108 
25109 /*
25110  * End of TCP Timers implementation.
25111  */
25112 
25113 /*
25114  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25115  * on the specified backing STREAMS q. Note, the caller may make the
25116  * decision to call based on the tcp_t.tcp_flow_stopped value which
25117  * when check outside the q's lock is only an advisory check ...
25118  */
25119 void
25120 tcp_setqfull(tcp_t *tcp)
25121 {
25122 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25123 	conn_t	*connp = tcp->tcp_connp;
25124 
25125 	if (tcp->tcp_closed)
25126 		return;
25127 
25128 	if (IPCL_IS_NONSTR(connp)) {
25129 		(*connp->conn_upcalls->su_txq_full)
25130 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25131 		tcp->tcp_flow_stopped = B_TRUE;
25132 	} else {
25133 		queue_t *q = tcp->tcp_wq;
25134 
25135 		if (!(q->q_flag & QFULL)) {
25136 			mutex_enter(QLOCK(q));
25137 			if (!(q->q_flag & QFULL)) {
25138 				/* still need to set QFULL */
25139 				q->q_flag |= QFULL;
25140 				tcp->tcp_flow_stopped = B_TRUE;
25141 				mutex_exit(QLOCK(q));
25142 				TCP_STAT(tcps, tcp_flwctl_on);
25143 			} else {
25144 				mutex_exit(QLOCK(q));
25145 			}
25146 		}
25147 	}
25148 }
25149 
25150 void
25151 tcp_clrqfull(tcp_t *tcp)
25152 {
25153 	conn_t  *connp = tcp->tcp_connp;
25154 
25155 	if (tcp->tcp_closed)
25156 		return;
25157 
25158 	if (IPCL_IS_NONSTR(connp)) {
25159 		(*connp->conn_upcalls->su_txq_full)
25160 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25161 		tcp->tcp_flow_stopped = B_FALSE;
25162 	} else {
25163 		queue_t *q = tcp->tcp_wq;
25164 
25165 		if (q->q_flag & QFULL) {
25166 			mutex_enter(QLOCK(q));
25167 			if (q->q_flag & QFULL) {
25168 				q->q_flag &= ~QFULL;
25169 				tcp->tcp_flow_stopped = B_FALSE;
25170 				mutex_exit(QLOCK(q));
25171 				if (q->q_flag & QWANTW)
25172 					qbackenable(q, 0);
25173 			} else {
25174 				mutex_exit(QLOCK(q));
25175 			}
25176 		}
25177 	}
25178 }
25179 
25180 /*
25181  * kstats related to squeues i.e. not per IP instance
25182  */
25183 static void *
25184 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
25185 {
25186 	kstat_t *ksp;
25187 
25188 	tcp_g_stat_t template = {
25189 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
25190 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
25191 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
25192 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
25193 	};
25194 
25195 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
25196 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25197 	    KSTAT_FLAG_VIRTUAL);
25198 
25199 	if (ksp == NULL)
25200 		return (NULL);
25201 
25202 	bcopy(&template, tcp_g_statp, sizeof (template));
25203 	ksp->ks_data = (void *)tcp_g_statp;
25204 
25205 	kstat_install(ksp);
25206 	return (ksp);
25207 }
25208 
25209 static void
25210 tcp_g_kstat_fini(kstat_t *ksp)
25211 {
25212 	if (ksp != NULL) {
25213 		kstat_delete(ksp);
25214 	}
25215 }
25216 
25217 
25218 static void *
25219 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
25220 {
25221 	kstat_t *ksp;
25222 
25223 	tcp_stat_t template = {
25224 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
25225 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
25226 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
25227 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
25228 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
25229 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
25230 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
25231 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
25232 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
25233 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
25234 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
25235 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
25236 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
25237 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
25238 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
25239 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
25240 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
25241 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
25242 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
25243 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
25244 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
25245 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
25246 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
25247 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
25248 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
25249 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
25250 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
25251 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
25252 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
25253 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
25254 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
25255 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
25256 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
25257 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
25258 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
25259 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
25260 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
25261 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
25262 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
25263 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
25264 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
25265 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
25266 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
25267 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
25268 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
25269 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
25270 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
25271 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
25272 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
25273 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
25274 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
25275 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
25276 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
25277 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
25278 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
25279 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
25280 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
25281 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
25282 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
25283 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
25284 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
25285 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
25286 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
25287 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
25288 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
25289 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
25290 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
25291 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
25292 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
25293 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
25294 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
25295 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
25296 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
25297 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
25298 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
25299 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
25300 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
25301 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
25302 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
25303 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
25304 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
25305 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
25306 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
25307 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
25308 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
25309 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
25310 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
25311 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
25312 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
25313 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
25314 	};
25315 
25316 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
25317 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25318 	    KSTAT_FLAG_VIRTUAL, stackid);
25319 
25320 	if (ksp == NULL)
25321 		return (NULL);
25322 
25323 	bcopy(&template, tcps_statisticsp, sizeof (template));
25324 	ksp->ks_data = (void *)tcps_statisticsp;
25325 	ksp->ks_private = (void *)(uintptr_t)stackid;
25326 
25327 	kstat_install(ksp);
25328 	return (ksp);
25329 }
25330 
25331 static void
25332 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
25333 {
25334 	if (ksp != NULL) {
25335 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25336 		kstat_delete_netstack(ksp, stackid);
25337 	}
25338 }
25339 
25340 /*
25341  * TCP Kstats implementation
25342  */
25343 static void *
25344 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
25345 {
25346 	kstat_t	*ksp;
25347 
25348 	tcp_named_kstat_t template = {
25349 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25350 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25351 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25352 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25353 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25354 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25355 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25356 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25357 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25358 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25359 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25360 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25361 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25362 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25363 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25364 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25365 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25366 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25367 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25368 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25369 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25370 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25371 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25372 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25373 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25374 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25375 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25376 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25377 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25378 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25379 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25380 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25381 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25382 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25383 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25384 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25385 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25386 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25387 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25388 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25389 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25390 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25391 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25392 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25393 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25394 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25395 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25396 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25397 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25398 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25399 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25400 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25401 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25402 	};
25403 
25404 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
25405 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
25406 
25407 	if (ksp == NULL)
25408 		return (NULL);
25409 
25410 	template.rtoAlgorithm.value.ui32 = 4;
25411 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
25412 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
25413 	template.maxConn.value.i32 = -1;
25414 
25415 	bcopy(&template, ksp->ks_data, sizeof (template));
25416 	ksp->ks_update = tcp_kstat_update;
25417 	ksp->ks_private = (void *)(uintptr_t)stackid;
25418 
25419 	kstat_install(ksp);
25420 	return (ksp);
25421 }
25422 
25423 static void
25424 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
25425 {
25426 	if (ksp != NULL) {
25427 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25428 		kstat_delete_netstack(ksp, stackid);
25429 	}
25430 }
25431 
25432 static int
25433 tcp_kstat_update(kstat_t *kp, int rw)
25434 {
25435 	tcp_named_kstat_t *tcpkp;
25436 	tcp_t		*tcp;
25437 	connf_t		*connfp;
25438 	conn_t		*connp;
25439 	int 		i;
25440 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
25441 	netstack_t	*ns;
25442 	tcp_stack_t	*tcps;
25443 	ip_stack_t	*ipst;
25444 
25445 	if ((kp == NULL) || (kp->ks_data == NULL))
25446 		return (EIO);
25447 
25448 	if (rw == KSTAT_WRITE)
25449 		return (EACCES);
25450 
25451 	ns = netstack_find_by_stackid(stackid);
25452 	if (ns == NULL)
25453 		return (-1);
25454 	tcps = ns->netstack_tcp;
25455 	if (tcps == NULL) {
25456 		netstack_rele(ns);
25457 		return (-1);
25458 	}
25459 
25460 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25461 
25462 	tcpkp->currEstab.value.ui32 = 0;
25463 
25464 	ipst = ns->netstack_ip;
25465 
25466 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25467 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25468 		connp = NULL;
25469 		while ((connp =
25470 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25471 			tcp = connp->conn_tcp;
25472 			switch (tcp_snmp_state(tcp)) {
25473 			case MIB2_TCP_established:
25474 			case MIB2_TCP_closeWait:
25475 				tcpkp->currEstab.value.ui32++;
25476 				break;
25477 			}
25478 		}
25479 	}
25480 
25481 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
25482 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
25483 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
25484 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
25485 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
25486 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
25487 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
25488 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
25489 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
25490 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
25491 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
25492 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
25493 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
25494 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
25495 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
25496 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
25497 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
25498 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
25499 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
25500 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
25501 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
25502 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
25503 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
25504 	tcpkp->inDataInorderSegs.value.ui32 =
25505 	    tcps->tcps_mib.tcpInDataInorderSegs;
25506 	tcpkp->inDataInorderBytes.value.ui32 =
25507 	    tcps->tcps_mib.tcpInDataInorderBytes;
25508 	tcpkp->inDataUnorderSegs.value.ui32 =
25509 	    tcps->tcps_mib.tcpInDataUnorderSegs;
25510 	tcpkp->inDataUnorderBytes.value.ui32 =
25511 	    tcps->tcps_mib.tcpInDataUnorderBytes;
25512 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
25513 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
25514 	tcpkp->inDataPartDupSegs.value.ui32 =
25515 	    tcps->tcps_mib.tcpInDataPartDupSegs;
25516 	tcpkp->inDataPartDupBytes.value.ui32 =
25517 	    tcps->tcps_mib.tcpInDataPartDupBytes;
25518 	tcpkp->inDataPastWinSegs.value.ui32 =
25519 	    tcps->tcps_mib.tcpInDataPastWinSegs;
25520 	tcpkp->inDataPastWinBytes.value.ui32 =
25521 	    tcps->tcps_mib.tcpInDataPastWinBytes;
25522 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
25523 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
25524 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
25525 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
25526 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
25527 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
25528 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
25529 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
25530 	tcpkp->timKeepaliveProbe.value.ui32 =
25531 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
25532 	tcpkp->timKeepaliveDrop.value.ui32 =
25533 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
25534 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
25535 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
25536 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
25537 	tcpkp->outSackRetransSegs.value.ui32 =
25538 	    tcps->tcps_mib.tcpOutSackRetransSegs;
25539 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
25540 
25541 	netstack_rele(ns);
25542 	return (0);
25543 }
25544 
25545 void
25546 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25547 {
25548 	uint16_t	hdr_len;
25549 	ipha_t		*ipha;
25550 	uint8_t		*nexthdrp;
25551 	tcph_t		*tcph;
25552 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
25553 
25554 	/* Already has an eager */
25555 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25556 		TCP_STAT(tcps, tcp_reinput_syn);
25557 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25558 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
25559 		return;
25560 	}
25561 
25562 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25563 	case IPV4_VERSION:
25564 		ipha = (ipha_t *)mp->b_rptr;
25565 		hdr_len = IPH_HDR_LENGTH(ipha);
25566 		break;
25567 	case IPV6_VERSION:
25568 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25569 		    &hdr_len, &nexthdrp)) {
25570 			CONN_DEC_REF(connp);
25571 			freemsg(mp);
25572 			return;
25573 		}
25574 		break;
25575 	}
25576 
25577 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25578 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25579 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25580 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25581 	}
25582 
25583 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25584 	    SQ_FILL, SQTAG_TCP_REINPUT);
25585 }
25586 
25587 static int
25588 tcp_squeue_switch(int val)
25589 {
25590 	int rval = SQ_FILL;
25591 
25592 	switch (val) {
25593 	case 1:
25594 		rval = SQ_NODRAIN;
25595 		break;
25596 	case 2:
25597 		rval = SQ_PROCESS;
25598 		break;
25599 	default:
25600 		break;
25601 	}
25602 	return (rval);
25603 }
25604 
25605 /*
25606  * This is called once for each squeue - globally for all stack
25607  * instances.
25608  */
25609 static void
25610 tcp_squeue_add(squeue_t *sqp)
25611 {
25612 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25613 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
25614 
25615 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25616 	tcp_time_wait->tcp_time_wait_tid =
25617 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
25618 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
25619 	    CALLOUT_FLAG_ROUNDUP);
25620 	if (tcp_free_list_max_cnt == 0) {
25621 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25622 		    max_ncpus : boot_max_ncpus);
25623 
25624 		/*
25625 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25626 		 */
25627 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25628 		    (tcp_ncpus * sizeof (tcp_t) * 100);
25629 	}
25630 	tcp_time_wait->tcp_free_list_cnt = 0;
25631 }
25632 
25633 static int
25634 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
25635 {
25636 	mblk_t	*ire_mp = NULL;
25637 	mblk_t	*syn_mp;
25638 	mblk_t	*mdti;
25639 	mblk_t	*lsoi;
25640 	int	retval;
25641 	tcph_t	*tcph;
25642 	cred_t	*ecr;
25643 	ts_label_t	*tsl;
25644 	uint32_t	mss;
25645 	conn_t	*connp = tcp->tcp_connp;
25646 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25647 
25648 	if (error == 0) {
25649 		/*
25650 		 * Adapt Multidata information, if any.  The
25651 		 * following tcp_mdt_update routine will free
25652 		 * the message.
25653 		 */
25654 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
25655 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
25656 			    b_rptr)->mdt_capab, B_TRUE);
25657 			freemsg(mdti);
25658 		}
25659 
25660 		/*
25661 		 * Check to update LSO information with tcp, and
25662 		 * tcp_lso_update routine will free the message.
25663 		 */
25664 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
25665 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
25666 			    b_rptr)->lso_capab);
25667 			freemsg(lsoi);
25668 		}
25669 
25670 		/* Get the IRE, if we had requested for it */
25671 		if (mp != NULL)
25672 			ire_mp = tcp_ire_mp(&mp);
25673 
25674 		if (tcp->tcp_hard_binding) {
25675 			tcp->tcp_hard_binding = B_FALSE;
25676 			tcp->tcp_hard_bound = B_TRUE;
25677 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
25678 			if (retval != 0) {
25679 				error = EADDRINUSE;
25680 				goto bind_failed;
25681 			}
25682 		} else {
25683 			if (ire_mp != NULL)
25684 				freeb(ire_mp);
25685 			goto after_syn_sent;
25686 		}
25687 
25688 		retval = tcp_adapt_ire(tcp, ire_mp);
25689 		if (ire_mp != NULL)
25690 			freeb(ire_mp);
25691 		if (retval == 0) {
25692 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
25693 			    ENETUNREACH : EADDRNOTAVAIL);
25694 			goto ipcl_rm;
25695 		}
25696 		/*
25697 		 * Don't let an endpoint connect to itself.
25698 		 * Also checked in tcp_connect() but that
25699 		 * check can't handle the case when the
25700 		 * local IP address is INADDR_ANY.
25701 		 */
25702 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25703 			if ((tcp->tcp_ipha->ipha_dst ==
25704 			    tcp->tcp_ipha->ipha_src) &&
25705 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25706 			    tcp->tcp_tcph->th_fport))) {
25707 				error = EADDRNOTAVAIL;
25708 				goto ipcl_rm;
25709 			}
25710 		} else {
25711 			if (IN6_ARE_ADDR_EQUAL(
25712 			    &tcp->tcp_ip6h->ip6_dst,
25713 			    &tcp->tcp_ip6h->ip6_src) &&
25714 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25715 			    tcp->tcp_tcph->th_fport))) {
25716 				error = EADDRNOTAVAIL;
25717 				goto ipcl_rm;
25718 			}
25719 		}
25720 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
25721 		/*
25722 		 * This should not be possible!  Just for
25723 		 * defensive coding...
25724 		 */
25725 		if (tcp->tcp_state != TCPS_SYN_SENT)
25726 			goto after_syn_sent;
25727 
25728 		if (is_system_labeled() &&
25729 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
25730 			error = EHOSTUNREACH;
25731 			goto ipcl_rm;
25732 		}
25733 
25734 		/*
25735 		 * tcp_adapt_ire() does not adjust
25736 		 * for TCP/IP header length.
25737 		 */
25738 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
25739 
25740 		/*
25741 		 * Just make sure our rwnd is at
25742 		 * least tcp_recv_hiwat_mss * MSS
25743 		 * large, and round up to the nearest
25744 		 * MSS.
25745 		 *
25746 		 * We do the round up here because
25747 		 * we need to get the interface
25748 		 * MTU first before we can do the
25749 		 * round up.
25750 		 */
25751 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
25752 		    tcps->tcps_recv_hiwat_minmss * mss);
25753 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
25754 		tcp_set_ws_value(tcp);
25755 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
25756 		    tcp->tcp_tcph->th_win);
25757 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
25758 			tcp->tcp_snd_ws_ok = B_TRUE;
25759 
25760 		/*
25761 		 * Set tcp_snd_ts_ok to true
25762 		 * so that tcp_xmit_mp will
25763 		 * include the timestamp
25764 		 * option in the SYN segment.
25765 		 */
25766 		if (tcps->tcps_tstamp_always ||
25767 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
25768 			tcp->tcp_snd_ts_ok = B_TRUE;
25769 		}
25770 
25771 		/*
25772 		 * tcp_snd_sack_ok can be set in
25773 		 * tcp_adapt_ire() if the sack metric
25774 		 * is set.  So check it here also.
25775 		 */
25776 		if (tcps->tcps_sack_permitted == 2 ||
25777 		    tcp->tcp_snd_sack_ok) {
25778 			if (tcp->tcp_sack_info == NULL) {
25779 				tcp->tcp_sack_info =
25780 				    kmem_cache_alloc(tcp_sack_info_cache,
25781 				    KM_SLEEP);
25782 			}
25783 			tcp->tcp_snd_sack_ok = B_TRUE;
25784 		}
25785 
25786 		/*
25787 		 * Should we use ECN?  Note that the current
25788 		 * default value (SunOS 5.9) of tcp_ecn_permitted
25789 		 * is 1.  The reason for doing this is that there
25790 		 * are equipments out there that will drop ECN
25791 		 * enabled IP packets.  Setting it to 1 avoids
25792 		 * compatibility problems.
25793 		 */
25794 		if (tcps->tcps_ecn_permitted == 2)
25795 			tcp->tcp_ecn_ok = B_TRUE;
25796 
25797 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
25798 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
25799 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
25800 		if (syn_mp) {
25801 			/*
25802 			 * cr contains the cred from the thread calling
25803 			 * connect().
25804 			 *
25805 			 * If no thread cred is available, use the
25806 			 * socket creator's cred instead. If still no
25807 			 * cred, drop the request rather than risk a
25808 			 * panic on production systems.
25809 			 */
25810 			if (cr == NULL) {
25811 				cr = CONN_CRED(connp);
25812 				pid = tcp->tcp_cpid;
25813 				ASSERT(cr != NULL);
25814 				if (cr != NULL) {
25815 					mblk_setcred(syn_mp, cr, pid);
25816 				} else {
25817 					error = ECONNABORTED;
25818 					goto ipcl_rm;
25819 				}
25820 
25821 			/*
25822 			 * If an effective security label exists for
25823 			 * the connection, create a copy of the thread's
25824 			 * cred but with the effective label attached.
25825 			 */
25826 			} else if (is_system_labeled() &&
25827 			    connp->conn_effective_cred != NULL &&
25828 			    (tsl = crgetlabel(connp->
25829 			    conn_effective_cred)) != NULL) {
25830 				if ((ecr = copycred_from_tslabel(cr,
25831 				    tsl, KM_NOSLEEP)) == NULL) {
25832 					error = ENOMEM;
25833 					goto ipcl_rm;
25834 				}
25835 				mblk_setcred(syn_mp, ecr, pid);
25836 				crfree(ecr);
25837 
25838 			/*
25839 			 * Default to using the thread's cred unchanged.
25840 			 */
25841 			} else {
25842 				mblk_setcred(syn_mp, cr, pid);
25843 			}
25844 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
25845 		}
25846 	after_syn_sent:
25847 		if (mp != NULL) {
25848 			ASSERT(mp->b_cont == NULL);
25849 			freeb(mp);
25850 		}
25851 		return (error);
25852 	} else {
25853 		/* error */
25854 		if (tcp->tcp_debug) {
25855 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
25856 			    "tcp_post_ip_bind: error == %d", error);
25857 		}
25858 		if (mp != NULL) {
25859 			freeb(mp);
25860 		}
25861 	}
25862 
25863 ipcl_rm:
25864 	/*
25865 	 * Need to unbind with classifier since we were just
25866 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
25867 	 */
25868 	tcp->tcp_hard_bound = B_FALSE;
25869 	tcp->tcp_hard_binding = B_FALSE;
25870 
25871 	ipcl_hash_remove(connp);
25872 
25873 bind_failed:
25874 	tcp->tcp_state = TCPS_IDLE;
25875 	if (tcp->tcp_ipversion == IPV4_VERSION)
25876 		tcp->tcp_ipha->ipha_src = 0;
25877 	else
25878 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
25879 	/*
25880 	 * Copy of the src addr. in tcp_t is needed since
25881 	 * the lookup funcs. can only look at tcp_t
25882 	 */
25883 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
25884 
25885 	tcph = tcp->tcp_tcph;
25886 	tcph->th_lport[0] = 0;
25887 	tcph->th_lport[1] = 0;
25888 	tcp_bind_hash_remove(tcp);
25889 	bzero(&connp->u_port, sizeof (connp->u_port));
25890 	/* blow away saved option results if any */
25891 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
25892 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
25893 
25894 	conn_delete_ire(tcp->tcp_connp, NULL);
25895 
25896 	return (error);
25897 }
25898 
25899 static int
25900 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
25901     boolean_t bind_to_req_port_only, cred_t *cr)
25902 {
25903 	in_port_t	mlp_port;
25904 	mlp_type_t 	addrtype, mlptype;
25905 	boolean_t	user_specified;
25906 	in_port_t	allocated_port;
25907 	in_port_t	requested_port = *requested_port_ptr;
25908 	conn_t		*connp;
25909 	zone_t		*zone;
25910 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25911 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
25912 
25913 	/*
25914 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
25915 	 */
25916 	if (cr == NULL)
25917 		cr = tcp->tcp_cred;
25918 	/*
25919 	 * Get a valid port (within the anonymous range and should not
25920 	 * be a privileged one) to use if the user has not given a port.
25921 	 * If multiple threads are here, they may all start with
25922 	 * with the same initial port. But, it should be fine as long as
25923 	 * tcp_bindi will ensure that no two threads will be assigned
25924 	 * the same port.
25925 	 *
25926 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
25927 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
25928 	 * unless TCP_ANONPRIVBIND option is set.
25929 	 */
25930 	mlptype = mlptSingle;
25931 	mlp_port = requested_port;
25932 	if (requested_port == 0) {
25933 		requested_port = tcp->tcp_anon_priv_bind ?
25934 		    tcp_get_next_priv_port(tcp) :
25935 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
25936 		    tcp, B_TRUE);
25937 		if (requested_port == 0) {
25938 			return (-TNOADDR);
25939 		}
25940 		user_specified = B_FALSE;
25941 
25942 		/*
25943 		 * If the user went through one of the RPC interfaces to create
25944 		 * this socket and RPC is MLP in this zone, then give him an
25945 		 * anonymous MLP.
25946 		 */
25947 		connp = tcp->tcp_connp;
25948 		if (connp->conn_anon_mlp && is_system_labeled()) {
25949 			zone = crgetzone(cr);
25950 			addrtype = tsol_mlp_addr_type(
25951 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
25952 			    IPV6_VERSION, &v6addr,
25953 			    tcps->tcps_netstack->netstack_ip);
25954 			if (addrtype == mlptSingle) {
25955 				return (-TNOADDR);
25956 			}
25957 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25958 			    PMAPPORT, addrtype);
25959 			mlp_port = PMAPPORT;
25960 		}
25961 	} else {
25962 		int i;
25963 		boolean_t priv = B_FALSE;
25964 
25965 		/*
25966 		 * If the requested_port is in the well-known privileged range,
25967 		 * verify that the stream was opened by a privileged user.
25968 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
25969 		 * but instead the code relies on:
25970 		 * - the fact that the address of the array and its size never
25971 		 *   changes
25972 		 * - the atomic assignment of the elements of the array
25973 		 */
25974 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
25975 			priv = B_TRUE;
25976 		} else {
25977 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
25978 				if (requested_port ==
25979 				    tcps->tcps_g_epriv_ports[i]) {
25980 					priv = B_TRUE;
25981 					break;
25982 				}
25983 			}
25984 		}
25985 		if (priv) {
25986 			if (secpolicy_net_privaddr(cr, requested_port,
25987 			    IPPROTO_TCP) != 0) {
25988 				if (tcp->tcp_debug) {
25989 					(void) strlog(TCP_MOD_ID, 0, 1,
25990 					    SL_ERROR|SL_TRACE,
25991 					    "tcp_bind: no priv for port %d",
25992 					    requested_port);
25993 				}
25994 				return (-TACCES);
25995 			}
25996 		}
25997 		user_specified = B_TRUE;
25998 
25999 		connp = tcp->tcp_connp;
26000 		if (is_system_labeled()) {
26001 			zone = crgetzone(cr);
26002 			addrtype = tsol_mlp_addr_type(
26003 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
26004 			    IPV6_VERSION, &v6addr,
26005 			    tcps->tcps_netstack->netstack_ip);
26006 			if (addrtype == mlptSingle) {
26007 				return (-TNOADDR);
26008 			}
26009 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26010 			    requested_port, addrtype);
26011 		}
26012 	}
26013 
26014 	if (mlptype != mlptSingle) {
26015 		if (secpolicy_net_bindmlp(cr) != 0) {
26016 			if (tcp->tcp_debug) {
26017 				(void) strlog(TCP_MOD_ID, 0, 1,
26018 				    SL_ERROR|SL_TRACE,
26019 				    "tcp_bind: no priv for multilevel port %d",
26020 				    requested_port);
26021 			}
26022 			return (-TACCES);
26023 		}
26024 
26025 		/*
26026 		 * If we're specifically binding a shared IP address and the
26027 		 * port is MLP on shared addresses, then check to see if this
26028 		 * zone actually owns the MLP.  Reject if not.
26029 		 */
26030 		if (mlptype == mlptShared && addrtype == mlptShared) {
26031 			/*
26032 			 * No need to handle exclusive-stack zones since
26033 			 * ALL_ZONES only applies to the shared stack.
26034 			 */
26035 			zoneid_t mlpzone;
26036 
26037 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26038 			    htons(mlp_port));
26039 			if (connp->conn_zoneid != mlpzone) {
26040 				if (tcp->tcp_debug) {
26041 					(void) strlog(TCP_MOD_ID, 0, 1,
26042 					    SL_ERROR|SL_TRACE,
26043 					    "tcp_bind: attempt to bind port "
26044 					    "%d on shared addr in zone %d "
26045 					    "(should be %d)",
26046 					    mlp_port, connp->conn_zoneid,
26047 					    mlpzone);
26048 				}
26049 				return (-TACCES);
26050 			}
26051 		}
26052 
26053 		if (!user_specified) {
26054 			int err;
26055 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26056 			    requested_port, B_TRUE);
26057 			if (err != 0) {
26058 				if (tcp->tcp_debug) {
26059 					(void) strlog(TCP_MOD_ID, 0, 1,
26060 					    SL_ERROR|SL_TRACE,
26061 					    "tcp_bind: cannot establish anon "
26062 					    "MLP for port %d",
26063 					    requested_port);
26064 				}
26065 				return (err);
26066 			}
26067 			connp->conn_anon_port = B_TRUE;
26068 		}
26069 		connp->conn_mlp_type = mlptype;
26070 	}
26071 
26072 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26073 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26074 
26075 	if (allocated_port == 0) {
26076 		connp->conn_mlp_type = mlptSingle;
26077 		if (connp->conn_anon_port) {
26078 			connp->conn_anon_port = B_FALSE;
26079 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26080 			    requested_port, B_FALSE);
26081 		}
26082 		if (bind_to_req_port_only) {
26083 			if (tcp->tcp_debug) {
26084 				(void) strlog(TCP_MOD_ID, 0, 1,
26085 				    SL_ERROR|SL_TRACE,
26086 				    "tcp_bind: requested addr busy");
26087 			}
26088 			return (-TADDRBUSY);
26089 		} else {
26090 			/* If we are out of ports, fail the bind. */
26091 			if (tcp->tcp_debug) {
26092 				(void) strlog(TCP_MOD_ID, 0, 1,
26093 				    SL_ERROR|SL_TRACE,
26094 				    "tcp_bind: out of ports?");
26095 			}
26096 			return (-TNOADDR);
26097 		}
26098 	}
26099 
26100 	/* Pass the allocated port back */
26101 	*requested_port_ptr = allocated_port;
26102 	return (0);
26103 }
26104 
26105 static int
26106 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26107     boolean_t bind_to_req_port_only)
26108 {
26109 	tcp_t	*tcp = connp->conn_tcp;
26110 	sin_t	*sin;
26111 	sin6_t  *sin6;
26112 	in_port_t requested_port;
26113 	ipaddr_t	v4addr;
26114 	in6_addr_t	v6addr;
26115 	uint_t	ipversion;
26116 	int	error = 0;
26117 
26118 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26119 
26120 	if (tcp->tcp_state == TCPS_BOUND) {
26121 		return (0);
26122 	} else if (tcp->tcp_state > TCPS_BOUND) {
26123 		if (tcp->tcp_debug) {
26124 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26125 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26126 		}
26127 		return (-TOUTSTATE);
26128 	}
26129 
26130 	ASSERT(sa != NULL && len != 0);
26131 
26132 	if (!OK_32PTR((char *)sa)) {
26133 		if (tcp->tcp_debug) {
26134 			(void) strlog(TCP_MOD_ID, 0, 1,
26135 			    SL_ERROR|SL_TRACE,
26136 			    "tcp_bind: bad address parameter, "
26137 			    "address %p, len %d",
26138 			    (void *)sa, len);
26139 		}
26140 		return (-TPROTO);
26141 	}
26142 
26143 	switch (len) {
26144 	case sizeof (sin_t):	/* Complete IPv4 address */
26145 		sin = (sin_t *)sa;
26146 		/*
26147 		 * With sockets sockfs will accept bogus sin_family in
26148 		 * bind() and replace it with the family used in the socket
26149 		 * call.
26150 		 */
26151 		if (sin->sin_family != AF_INET ||
26152 		    tcp->tcp_family != AF_INET) {
26153 			return (EAFNOSUPPORT);
26154 		}
26155 		requested_port = ntohs(sin->sin_port);
26156 		ipversion = IPV4_VERSION;
26157 		v4addr = sin->sin_addr.s_addr;
26158 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26159 		break;
26160 
26161 	case sizeof (sin6_t): /* Complete IPv6 address */
26162 		sin6 = (sin6_t *)sa;
26163 		if (sin6->sin6_family != AF_INET6 ||
26164 		    tcp->tcp_family != AF_INET6) {
26165 			return (EAFNOSUPPORT);
26166 		}
26167 		requested_port = ntohs(sin6->sin6_port);
26168 		ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26169 		    IPV4_VERSION : IPV6_VERSION;
26170 		v6addr = sin6->sin6_addr;
26171 		break;
26172 
26173 	default:
26174 		if (tcp->tcp_debug) {
26175 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26176 			    "tcp_bind: bad address length, %d", len);
26177 		}
26178 		return (EAFNOSUPPORT);
26179 		/* return (-TBADADDR); */
26180 	}
26181 
26182 	tcp->tcp_bound_source_v6 = v6addr;
26183 
26184 	/* Check for change in ipversion */
26185 	if (tcp->tcp_ipversion != ipversion) {
26186 		ASSERT(tcp->tcp_family == AF_INET6);
26187 		error = (ipversion == IPV6_VERSION) ?
26188 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26189 		if (error) {
26190 			return (ENOMEM);
26191 		}
26192 	}
26193 
26194 	/*
26195 	 * Initialize family specific fields. Copy of the src addr.
26196 	 * in tcp_t is needed for the lookup funcs.
26197 	 */
26198 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26199 		tcp->tcp_ip6h->ip6_src = v6addr;
26200 	} else {
26201 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
26202 	}
26203 	tcp->tcp_ip_src_v6 = v6addr;
26204 
26205 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
26206 
26207 	error = tcp_bind_select_lport(tcp, &requested_port,
26208 	    bind_to_req_port_only, cr);
26209 
26210 	return (error);
26211 }
26212 
26213 /*
26214  * Return unix error is tli error is TSYSERR, otherwise return a negative
26215  * tli error.
26216  */
26217 int
26218 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26219     boolean_t bind_to_req_port_only)
26220 {
26221 	int error;
26222 	tcp_t *tcp = connp->conn_tcp;
26223 
26224 	if (tcp->tcp_state >= TCPS_BOUND) {
26225 		if (tcp->tcp_debug) {
26226 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26227 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26228 		}
26229 		return (-TOUTSTATE);
26230 	}
26231 
26232 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
26233 	if (error != 0)
26234 		return (error);
26235 
26236 	ASSERT(tcp->tcp_state == TCPS_BOUND);
26237 
26238 	tcp->tcp_conn_req_max = 0;
26239 
26240 	if (tcp->tcp_family == AF_INET6) {
26241 		ASSERT(tcp->tcp_connp->conn_af_isv6);
26242 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
26243 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
26244 	} else {
26245 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
26246 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
26247 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
26248 	}
26249 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
26250 }
26251 
26252 int
26253 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
26254     socklen_t len, cred_t *cr)
26255 {
26256 	int 		error;
26257 	conn_t		*connp = (conn_t *)proto_handle;
26258 	squeue_t	*sqp = connp->conn_sqp;
26259 
26260 	/* All Solaris components should pass a cred for this operation. */
26261 	ASSERT(cr != NULL);
26262 
26263 	ASSERT(sqp != NULL);
26264 	ASSERT(connp->conn_upper_handle != NULL);
26265 
26266 	error = squeue_synch_enter(sqp, connp, NULL);
26267 	if (error != 0) {
26268 		/* failed to enter */
26269 		return (ENOSR);
26270 	}
26271 
26272 	/* binding to a NULL address really means unbind */
26273 	if (sa == NULL) {
26274 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
26275 			error = tcp_do_unbind(connp);
26276 		else
26277 			error = EINVAL;
26278 	} else {
26279 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
26280 	}
26281 
26282 	squeue_synch_exit(sqp, connp);
26283 
26284 	if (error < 0) {
26285 		if (error == -TOUTSTATE)
26286 			error = EINVAL;
26287 		else
26288 			error = proto_tlitosyserr(-error);
26289 	}
26290 
26291 	return (error);
26292 }
26293 
26294 /*
26295  * If the return value from this function is positive, it's a UNIX error.
26296  * Otherwise, if it's negative, then the absolute value is a TLI error.
26297  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
26298  */
26299 int
26300 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
26301     cred_t *cr, pid_t pid)
26302 {
26303 	tcp_t		*tcp = connp->conn_tcp;
26304 	sin_t		*sin = (sin_t *)sa;
26305 	sin6_t		*sin6 = (sin6_t *)sa;
26306 	ipaddr_t	*dstaddrp;
26307 	in_port_t	dstport;
26308 	uint_t		srcid;
26309 	int		error = 0;
26310 
26311 	switch (len) {
26312 	default:
26313 		/*
26314 		 * Should never happen
26315 		 */
26316 		return (EINVAL);
26317 
26318 	case sizeof (sin_t):
26319 		sin = (sin_t *)sa;
26320 		if (sin->sin_port == 0) {
26321 			return (-TBADADDR);
26322 		}
26323 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
26324 			return (EAFNOSUPPORT);
26325 		}
26326 		break;
26327 
26328 	case sizeof (sin6_t):
26329 		sin6 = (sin6_t *)sa;
26330 		if (sin6->sin6_port == 0) {
26331 			return (-TBADADDR);
26332 		}
26333 		break;
26334 	}
26335 	/*
26336 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
26337 	 * make sure that the template IP header in the tcp structure is an
26338 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
26339 	 * need to this before we call tcp_bindi() so that the port lookup
26340 	 * code will look for ports in the correct port space (IPv4 and
26341 	 * IPv6 have separate port spaces).
26342 	 */
26343 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
26344 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26345 		int err = 0;
26346 
26347 		err = tcp_header_init_ipv4(tcp);
26348 			if (err != 0) {
26349 				error = ENOMEM;
26350 				goto connect_failed;
26351 			}
26352 		if (tcp->tcp_lport != 0)
26353 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
26354 	}
26355 
26356 	switch (tcp->tcp_state) {
26357 	case TCPS_LISTEN:
26358 		/*
26359 		 * Listening sockets are not allowed to issue connect().
26360 		 */
26361 		if (IPCL_IS_NONSTR(connp))
26362 			return (EOPNOTSUPP);
26363 		/* FALLTHRU */
26364 	case TCPS_IDLE:
26365 		/*
26366 		 * We support quick connect, refer to comments in
26367 		 * tcp_connect_*()
26368 		 */
26369 		/* FALLTHRU */
26370 	case TCPS_BOUND:
26371 		/*
26372 		 * We must bump the generation before the operation start.
26373 		 * This is done to ensure that any upcall made later on sends
26374 		 * up the right generation to the socket.
26375 		 */
26376 		SOCK_CONNID_BUMP(tcp->tcp_connid);
26377 
26378 		if (tcp->tcp_family == AF_INET6) {
26379 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26380 				return (tcp_connect_ipv6(tcp,
26381 				    &sin6->sin6_addr,
26382 				    sin6->sin6_port, sin6->sin6_flowinfo,
26383 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
26384 				    cr, pid));
26385 			}
26386 			/*
26387 			 * Destination adress is mapped IPv6 address.
26388 			 * Source bound address should be unspecified or
26389 			 * IPv6 mapped address as well.
26390 			 */
26391 			if (!IN6_IS_ADDR_UNSPECIFIED(
26392 			    &tcp->tcp_bound_source_v6) &&
26393 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
26394 				return (EADDRNOTAVAIL);
26395 			}
26396 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
26397 			dstport = sin6->sin6_port;
26398 			srcid = sin6->__sin6_src_id;
26399 		} else {
26400 			dstaddrp = &sin->sin_addr.s_addr;
26401 			dstport = sin->sin_port;
26402 			srcid = 0;
26403 		}
26404 
26405 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
26406 		    pid);
26407 		break;
26408 	default:
26409 		return (-TOUTSTATE);
26410 	}
26411 	/*
26412 	 * Note: Code below is the "failure" case
26413 	 */
26414 connect_failed:
26415 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26416 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26417 	return (error);
26418 }
26419 
26420 int
26421 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
26422     socklen_t len, sock_connid_t *id, cred_t *cr)
26423 {
26424 	conn_t		*connp = (conn_t *)proto_handle;
26425 	tcp_t		*tcp = connp->conn_tcp;
26426 	squeue_t	*sqp = connp->conn_sqp;
26427 	int		error;
26428 
26429 	ASSERT(connp->conn_upper_handle != NULL);
26430 
26431 	/* All Solaris components should pass a cred for this operation. */
26432 	ASSERT(cr != NULL);
26433 
26434 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
26435 	if (error != 0) {
26436 		return (error);
26437 	}
26438 
26439 	error = squeue_synch_enter(sqp, connp, NULL);
26440 	if (error != 0) {
26441 		/* failed to enter */
26442 		return (ENOSR);
26443 	}
26444 
26445 	/*
26446 	 * TCP supports quick connect, so no need to do an implicit bind
26447 	 */
26448 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
26449 	if (error == 0) {
26450 		*id = connp->conn_tcp->tcp_connid;
26451 	} else if (error < 0) {
26452 		if (error == -TOUTSTATE) {
26453 			switch (connp->conn_tcp->tcp_state) {
26454 			case TCPS_SYN_SENT:
26455 				error = EALREADY;
26456 				break;
26457 			case TCPS_ESTABLISHED:
26458 				error = EISCONN;
26459 				break;
26460 			case TCPS_LISTEN:
26461 				error = EOPNOTSUPP;
26462 				break;
26463 			default:
26464 				error = EINVAL;
26465 				break;
26466 			}
26467 		} else {
26468 			error = proto_tlitosyserr(-error);
26469 		}
26470 	}
26471 
26472 	if (tcp->tcp_loopback) {
26473 		struct sock_proto_props sopp;
26474 
26475 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
26476 		sopp.sopp_loopback = B_TRUE;
26477 
26478 		(*connp->conn_upcalls->su_set_proto_props)(
26479 		    connp->conn_upper_handle, &sopp);
26480 	}
26481 done:
26482 	squeue_synch_exit(sqp, connp);
26483 
26484 	return ((error == 0) ? EINPROGRESS : error);
26485 }
26486 
26487 /* ARGSUSED */
26488 sock_lower_handle_t
26489 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
26490     uint_t *smodep, int *errorp, int flags, cred_t *credp)
26491 {
26492 	conn_t		*connp;
26493 	boolean_t	isv6 = family == AF_INET6;
26494 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
26495 	    (proto != 0 && proto != IPPROTO_TCP)) {
26496 		*errorp = EPROTONOSUPPORT;
26497 		return (NULL);
26498 	}
26499 
26500 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
26501 	if (connp == NULL) {
26502 		return (NULL);
26503 	}
26504 
26505 	/*
26506 	 * Put the ref for TCP. Ref for IP was already put
26507 	 * by ipcl_conn_create. Also Make the conn_t globally
26508 	 * visible to walkers
26509 	 */
26510 	mutex_enter(&connp->conn_lock);
26511 	CONN_INC_REF_LOCKED(connp);
26512 	ASSERT(connp->conn_ref == 2);
26513 	connp->conn_state_flags &= ~CONN_INCIPIENT;
26514 
26515 	connp->conn_flags |= IPCL_NONSTR;
26516 	mutex_exit(&connp->conn_lock);
26517 
26518 	ASSERT(errorp != NULL);
26519 	*errorp = 0;
26520 	*sock_downcalls = &sock_tcp_downcalls;
26521 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
26522 	    SM_SENDFILESUPP;
26523 
26524 	return ((sock_lower_handle_t)connp);
26525 }
26526 
26527 /* ARGSUSED */
26528 void
26529 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
26530     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
26531 {
26532 	conn_t *connp = (conn_t *)proto_handle;
26533 	struct sock_proto_props sopp;
26534 
26535 	ASSERT(connp->conn_upper_handle == NULL);
26536 
26537 	/* All Solaris components should pass a cred for this operation. */
26538 	ASSERT(cr != NULL);
26539 
26540 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
26541 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
26542 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
26543 
26544 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
26545 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
26546 	sopp.sopp_maxpsz = INFPSZ;
26547 	sopp.sopp_maxblk = INFPSZ;
26548 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
26549 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
26550 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
26551 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
26552 	    tcp_rinfo.mi_minpsz;
26553 
26554 	connp->conn_upcalls = sock_upcalls;
26555 	connp->conn_upper_handle = sock_handle;
26556 
26557 	ASSERT(connp->conn_tcp->tcp_recv_hiwater != 0 &&
26558 	    connp->conn_tcp->tcp_recv_hiwater == connp->conn_tcp->tcp_rwnd);
26559 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
26560 }
26561 
26562 /* ARGSUSED */
26563 int
26564 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
26565 {
26566 	conn_t *connp = (conn_t *)proto_handle;
26567 
26568 	ASSERT(connp->conn_upper_handle != NULL);
26569 
26570 	/* All Solaris components should pass a cred for this operation. */
26571 	ASSERT(cr != NULL);
26572 
26573 	tcp_close_common(connp, flags);
26574 
26575 	ip_free_helper_stream(connp);
26576 
26577 	/*
26578 	 * Drop IP's reference on the conn. This is the last reference
26579 	 * on the connp if the state was less than established. If the
26580 	 * connection has gone into timewait state, then we will have
26581 	 * one ref for the TCP and one more ref (total of two) for the
26582 	 * classifier connected hash list (a timewait connections stays
26583 	 * in connected hash till closed).
26584 	 *
26585 	 * We can't assert the references because there might be other
26586 	 * transient reference places because of some walkers or queued
26587 	 * packets in squeue for the timewait state.
26588 	 */
26589 	CONN_DEC_REF(connp);
26590 	return (0);
26591 }
26592 
26593 /* ARGSUSED */
26594 int
26595 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
26596     cred_t *cr)
26597 {
26598 	tcp_t		*tcp;
26599 	uint32_t	msize;
26600 	conn_t *connp = (conn_t *)proto_handle;
26601 	int32_t		tcpstate;
26602 
26603 	/* All Solaris components should pass a cred for this operation. */
26604 	ASSERT(cr != NULL);
26605 
26606 	ASSERT(connp->conn_ref >= 2);
26607 	ASSERT(connp->conn_upper_handle != NULL);
26608 
26609 	if (msg->msg_controllen != 0) {
26610 		return (EOPNOTSUPP);
26611 
26612 	}
26613 	switch (DB_TYPE(mp)) {
26614 	case M_DATA:
26615 		tcp = connp->conn_tcp;
26616 		ASSERT(tcp != NULL);
26617 
26618 		tcpstate = tcp->tcp_state;
26619 		if (tcpstate < TCPS_ESTABLISHED) {
26620 			freemsg(mp);
26621 			return (ENOTCONN);
26622 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
26623 			freemsg(mp);
26624 			return (EPIPE);
26625 		}
26626 
26627 		msize = msgdsize(mp);
26628 
26629 		mutex_enter(&tcp->tcp_non_sq_lock);
26630 		tcp->tcp_squeue_bytes += msize;
26631 		/*
26632 		 * Squeue Flow Control
26633 		 */
26634 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
26635 			tcp_setqfull(tcp);
26636 		}
26637 		mutex_exit(&tcp->tcp_non_sq_lock);
26638 
26639 		/*
26640 		 * The application may pass in an address in the msghdr, but
26641 		 * we ignore the address on connection-oriented sockets.
26642 		 * Just like BSD this code does not generate an error for
26643 		 * TCP (a CONNREQUIRED socket) when sending to an address
26644 		 * passed in with sendto/sendmsg. Instead the data is
26645 		 * delivered on the connection as if no address had been
26646 		 * supplied.
26647 		 */
26648 		CONN_INC_REF(connp);
26649 
26650 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
26651 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
26652 			    tcp_output_urgent, connp, tcp_squeue_flag,
26653 			    SQTAG_TCP_OUTPUT);
26654 		} else {
26655 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
26656 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
26657 		}
26658 
26659 		return (0);
26660 
26661 	default:
26662 		ASSERT(0);
26663 	}
26664 
26665 	freemsg(mp);
26666 	return (0);
26667 }
26668 
26669 /* ARGSUSED */
26670 void
26671 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
26672 {
26673 	int len;
26674 	uint32_t msize;
26675 	conn_t *connp = (conn_t *)arg;
26676 	tcp_t *tcp = connp->conn_tcp;
26677 
26678 	msize = msgdsize(mp);
26679 
26680 	len = msize - 1;
26681 	if (len < 0) {
26682 		freemsg(mp);
26683 		return;
26684 	}
26685 
26686 	/*
26687 	 * Try to force urgent data out on the wire. Even if we have unsent
26688 	 * data this will at least send the urgent flag.
26689 	 * XXX does not handle more flag correctly.
26690 	 */
26691 	len += tcp->tcp_unsent;
26692 	len += tcp->tcp_snxt;
26693 	tcp->tcp_urg = len;
26694 	tcp->tcp_valid_bits |= TCP_URG_VALID;
26695 
26696 	/* Bypass tcp protocol for fused tcp loopback */
26697 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
26698 		return;
26699 
26700 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
26701 	if (DB_TYPE(mp) != M_DATA) {
26702 		mblk_t *mp1 = mp;
26703 		ASSERT(!IPCL_IS_NONSTR(connp));
26704 		mp = mp->b_cont;
26705 		freeb(mp1);
26706 	}
26707 	tcp_wput_data(tcp, mp, B_TRUE);
26708 }
26709 
26710 /* ARGSUSED */
26711 int
26712 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26713     socklen_t *addrlenp, cred_t *cr)
26714 {
26715 	conn_t	*connp = (conn_t *)proto_handle;
26716 	tcp_t	*tcp = connp->conn_tcp;
26717 
26718 	ASSERT(connp->conn_upper_handle != NULL);
26719 	/* All Solaris components should pass a cred for this operation. */
26720 	ASSERT(cr != NULL);
26721 
26722 	ASSERT(tcp != NULL);
26723 
26724 	return (tcp_do_getpeername(tcp, addr, addrlenp));
26725 }
26726 
26727 /* ARGSUSED */
26728 int
26729 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26730     socklen_t *addrlenp, cred_t *cr)
26731 {
26732 	conn_t	*connp = (conn_t *)proto_handle;
26733 	tcp_t	*tcp = connp->conn_tcp;
26734 
26735 	/* All Solaris components should pass a cred for this operation. */
26736 	ASSERT(cr != NULL);
26737 
26738 	ASSERT(connp->conn_upper_handle != NULL);
26739 
26740 	return (tcp_do_getsockname(tcp, addr, addrlenp));
26741 }
26742 
26743 /*
26744  * tcp_fallback
26745  *
26746  * A direct socket is falling back to using STREAMS. The queue
26747  * that is being passed down was created using tcp_open() with
26748  * the SO_FALLBACK flag set. As a result, the queue is not
26749  * associated with a conn, and the q_ptrs instead contain the
26750  * dev and minor area that should be used.
26751  *
26752  * The 'issocket' flag indicates whether the FireEngine
26753  * optimizations should be used. The common case would be that
26754  * optimizations are enabled, and they might be subsequently
26755  * disabled using the _SIOCSOCKFALLBACK ioctl.
26756  */
26757 
26758 /*
26759  * An active connection is falling back to TPI. Gather all the information
26760  * required by the STREAM head and TPI sonode and send it up.
26761  */
26762 void
26763 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
26764     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
26765 {
26766 	conn_t			*connp = tcp->tcp_connp;
26767 	struct stroptions	*stropt;
26768 	struct T_capability_ack tca;
26769 	struct sockaddr_in6	laddr, faddr;
26770 	socklen_t 		laddrlen, faddrlen;
26771 	short			opts;
26772 	int			error;
26773 	mblk_t			*mp;
26774 
26775 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
26776 	connp->conn_minor_arena = WR(q)->q_ptr;
26777 
26778 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
26779 
26780 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
26781 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
26782 
26783 	WR(q)->q_qinfo = &tcp_sock_winit;
26784 
26785 	if (!issocket)
26786 		tcp_use_pure_tpi(tcp);
26787 
26788 	/*
26789 	 * free the helper stream
26790 	 */
26791 	ip_free_helper_stream(connp);
26792 
26793 	/*
26794 	 * Notify the STREAM head about options
26795 	 */
26796 	DB_TYPE(stropt_mp) = M_SETOPTS;
26797 	stropt = (struct stroptions *)stropt_mp->b_rptr;
26798 	stropt_mp->b_wptr += sizeof (struct stroptions);
26799 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
26800 
26801 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
26802 	    tcp->tcp_tcps->tcps_wroff_xtra);
26803 	if (tcp->tcp_snd_sack_ok)
26804 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
26805 	stropt->so_hiwat = tcp->tcp_recv_hiwater;
26806 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
26807 
26808 	putnext(RD(q), stropt_mp);
26809 
26810 	/*
26811 	 * Collect the information needed to sync with the sonode
26812 	 */
26813 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
26814 
26815 	laddrlen = faddrlen = sizeof (sin6_t);
26816 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
26817 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
26818 	if (error != 0)
26819 		faddrlen = 0;
26820 
26821 	opts = 0;
26822 	if (tcp->tcp_oobinline)
26823 		opts |= SO_OOBINLINE;
26824 	if (tcp->tcp_dontroute)
26825 		opts |= SO_DONTROUTE;
26826 
26827 	/*
26828 	 * Notify the socket that the protocol is now quiescent,
26829 	 * and it's therefore safe move data from the socket
26830 	 * to the stream head.
26831 	 */
26832 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
26833 	    (struct sockaddr *)&laddr, laddrlen,
26834 	    (struct sockaddr *)&faddr, faddrlen, opts);
26835 
26836 	while ((mp = tcp->tcp_rcv_list) != NULL) {
26837 		tcp->tcp_rcv_list = mp->b_next;
26838 		mp->b_next = NULL;
26839 		putnext(q, mp);
26840 	}
26841 	tcp->tcp_rcv_last_head = NULL;
26842 	tcp->tcp_rcv_last_tail = NULL;
26843 	tcp->tcp_rcv_cnt = 0;
26844 }
26845 
26846 /*
26847  * An eager is falling back to TPI. All we have to do is send
26848  * up a T_CONN_IND.
26849  */
26850 void
26851 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
26852 {
26853 	tcp_t *listener = eager->tcp_listener;
26854 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
26855 
26856 	ASSERT(listener != NULL);
26857 	ASSERT(mp != NULL);
26858 
26859 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
26860 
26861 	/*
26862 	 * TLI/XTI applications will get confused by
26863 	 * sending eager as an option since it violates
26864 	 * the option semantics. So remove the eager as
26865 	 * option since TLI/XTI app doesn't need it anyway.
26866 	 */
26867 	if (!direct_sockfs) {
26868 		struct T_conn_ind *conn_ind;
26869 
26870 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
26871 		conn_ind->OPT_length = 0;
26872 		conn_ind->OPT_offset = 0;
26873 	}
26874 
26875 	/*
26876 	 * Sockfs guarantees that the listener will not be closed
26877 	 * during fallback. So we can safely use the listener's queue.
26878 	 */
26879 	putnext(listener->tcp_rq, mp);
26880 }
26881 
26882 int
26883 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
26884     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
26885 {
26886 	tcp_t			*tcp;
26887 	conn_t 			*connp = (conn_t *)proto_handle;
26888 	int			error;
26889 	mblk_t			*stropt_mp;
26890 	mblk_t			*ordrel_mp;
26891 
26892 	tcp = connp->conn_tcp;
26893 
26894 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
26895 	    NULL);
26896 
26897 	/* Pre-allocate the T_ordrel_ind mblk. */
26898 	ASSERT(tcp->tcp_ordrel_mp == NULL);
26899 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
26900 	    STR_NOSIG, NULL);
26901 	ordrel_mp->b_datap->db_type = M_PROTO;
26902 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
26903 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
26904 
26905 	/*
26906 	 * Enter the squeue so that no new packets can come in
26907 	 */
26908 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
26909 	if (error != 0) {
26910 		/* failed to enter, free all the pre-allocated messages. */
26911 		freeb(stropt_mp);
26912 		freeb(ordrel_mp);
26913 		/*
26914 		 * We cannot process the eager, so at least send out a
26915 		 * RST so the peer can reconnect.
26916 		 */
26917 		if (tcp->tcp_listener != NULL) {
26918 			(void) tcp_eager_blowoff(tcp->tcp_listener,
26919 			    tcp->tcp_conn_req_seqnum);
26920 		}
26921 		return (ENOMEM);
26922 	}
26923 
26924 	/*
26925 	 * Both endpoints must be of the same type (either STREAMS or
26926 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
26927 	 * we have to unfuse.
26928 	 */
26929 	if (tcp->tcp_fused)
26930 		tcp_unfuse(tcp);
26931 
26932 	/*
26933 	 * No longer a direct socket
26934 	 */
26935 	connp->conn_flags &= ~IPCL_NONSTR;
26936 	tcp->tcp_ordrel_mp = ordrel_mp;
26937 
26938 	if (tcp->tcp_listener != NULL) {
26939 		/* The eager will deal with opts when accept() is called */
26940 		freeb(stropt_mp);
26941 		tcp_fallback_eager(tcp, direct_sockfs);
26942 	} else {
26943 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
26944 		    quiesced_cb);
26945 	}
26946 
26947 	/*
26948 	 * There should be atleast two ref's (IP + TCP)
26949 	 */
26950 	ASSERT(connp->conn_ref >= 2);
26951 	squeue_synch_exit(connp->conn_sqp, connp);
26952 
26953 	return (0);
26954 }
26955 
26956 /* ARGSUSED */
26957 static void
26958 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
26959 {
26960 	conn_t 	*connp = (conn_t *)arg;
26961 	tcp_t	*tcp = connp->conn_tcp;
26962 
26963 	freemsg(mp);
26964 
26965 	if (tcp->tcp_fused)
26966 		tcp_unfuse(tcp);
26967 
26968 	if (tcp_xmit_end(tcp) != 0) {
26969 		/*
26970 		 * We were crossing FINs and got a reset from
26971 		 * the other side. Just ignore it.
26972 		 */
26973 		if (tcp->tcp_debug) {
26974 			(void) strlog(TCP_MOD_ID, 0, 1,
26975 			    SL_ERROR|SL_TRACE,
26976 			    "tcp_shutdown_output() out of state %s",
26977 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
26978 		}
26979 	}
26980 }
26981 
26982 /* ARGSUSED */
26983 int
26984 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
26985 {
26986 	conn_t  *connp = (conn_t *)proto_handle;
26987 	tcp_t   *tcp = connp->conn_tcp;
26988 
26989 	ASSERT(connp->conn_upper_handle != NULL);
26990 
26991 	/* All Solaris components should pass a cred for this operation. */
26992 	ASSERT(cr != NULL);
26993 
26994 	/*
26995 	 * X/Open requires that we check the connected state.
26996 	 */
26997 	if (tcp->tcp_state < TCPS_SYN_SENT)
26998 		return (ENOTCONN);
26999 
27000 	/* shutdown the send side */
27001 	if (how != SHUT_RD) {
27002 		mblk_t *bp;
27003 
27004 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27005 		CONN_INC_REF(connp);
27006 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27007 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27008 
27009 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27010 		    SOCK_OPCTL_SHUT_SEND, 0);
27011 	}
27012 
27013 	/* shutdown the recv side */
27014 	if (how != SHUT_WR)
27015 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27016 		    SOCK_OPCTL_SHUT_RECV, 0);
27017 
27018 	return (0);
27019 }
27020 
27021 /*
27022  * SOP_LISTEN() calls into tcp_listen().
27023  */
27024 /* ARGSUSED */
27025 int
27026 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27027 {
27028 	conn_t	*connp = (conn_t *)proto_handle;
27029 	int 	error;
27030 	squeue_t *sqp = connp->conn_sqp;
27031 
27032 	ASSERT(connp->conn_upper_handle != NULL);
27033 
27034 	/* All Solaris components should pass a cred for this operation. */
27035 	ASSERT(cr != NULL);
27036 
27037 	error = squeue_synch_enter(sqp, connp, NULL);
27038 	if (error != 0) {
27039 		/* failed to enter */
27040 		return (ENOBUFS);
27041 	}
27042 
27043 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
27044 	if (error == 0) {
27045 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27046 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27047 	} else if (error < 0) {
27048 		if (error == -TOUTSTATE)
27049 			error = EINVAL;
27050 		else
27051 			error = proto_tlitosyserr(-error);
27052 	}
27053 	squeue_synch_exit(sqp, connp);
27054 	return (error);
27055 }
27056 
27057 static int
27058 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
27059     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
27060 {
27061 	tcp_t		*tcp = connp->conn_tcp;
27062 	int		error = 0;
27063 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27064 
27065 	/* All Solaris components should pass a cred for this operation. */
27066 	ASSERT(cr != NULL);
27067 
27068 	if (tcp->tcp_state >= TCPS_BOUND) {
27069 		if ((tcp->tcp_state == TCPS_BOUND ||
27070 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27071 			/*
27072 			 * Handle listen() increasing backlog.
27073 			 * This is more "liberal" then what the TPI spec
27074 			 * requires but is needed to avoid a t_unbind
27075 			 * when handling listen() since the port number
27076 			 * might be "stolen" between the unbind and bind.
27077 			 */
27078 			goto do_listen;
27079 		}
27080 		if (tcp->tcp_debug) {
27081 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27082 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27083 		}
27084 		return (-TOUTSTATE);
27085 	} else {
27086 		if (sa == NULL) {
27087 			sin6_t	addr;
27088 			sin_t *sin;
27089 			sin6_t *sin6;
27090 
27091 			ASSERT(IPCL_IS_NONSTR(connp));
27092 
27093 			/* Do an implicit bind: Request for a generic port. */
27094 			if (tcp->tcp_family == AF_INET) {
27095 				len = sizeof (sin_t);
27096 				sin = (sin_t *)&addr;
27097 				*sin = sin_null;
27098 				sin->sin_family = AF_INET;
27099 			} else {
27100 				ASSERT(tcp->tcp_family == AF_INET6);
27101 				len = sizeof (sin6_t);
27102 				sin6 = (sin6_t *)&addr;
27103 				*sin6 = sin6_null;
27104 				sin6->sin6_family = AF_INET6;
27105 			}
27106 			sa = (struct sockaddr *)&addr;
27107 		}
27108 
27109 		error = tcp_bind_check(connp, sa, len, cr,
27110 		    bind_to_req_port_only);
27111 		if (error)
27112 			return (error);
27113 		/* Fall through and do the fanout insertion */
27114 	}
27115 
27116 do_listen:
27117 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27118 	tcp->tcp_conn_req_max = backlog;
27119 	if (tcp->tcp_conn_req_max) {
27120 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27121 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27122 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27123 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27124 		/*
27125 		 * If this is a listener, do not reset the eager list
27126 		 * and other stuffs.  Note that we don't check if the
27127 		 * existing eager list meets the new tcp_conn_req_max
27128 		 * requirement.
27129 		 */
27130 		if (tcp->tcp_state != TCPS_LISTEN) {
27131 			tcp->tcp_state = TCPS_LISTEN;
27132 			/* Initialize the chain. Don't need the eager_lock */
27133 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27134 			tcp->tcp_eager_next_drop_q0 = tcp;
27135 			tcp->tcp_eager_prev_drop_q0 = tcp;
27136 			tcp->tcp_second_ctimer_threshold =
27137 			    tcps->tcps_ip_abort_linterval;
27138 		}
27139 	}
27140 
27141 	/*
27142 	 * We can call ip_bind directly, the processing continues
27143 	 * in tcp_post_ip_bind().
27144 	 *
27145 	 * We need to make sure that the conn_recv is set to a non-null
27146 	 * value before we insert the conn into the classifier table.
27147 	 * This is to avoid a race with an incoming packet which does an
27148 	 * ipcl_classify().
27149 	 */
27150 	connp->conn_recv = tcp_conn_request;
27151 	if (tcp->tcp_family == AF_INET) {
27152 		error = ip_proto_bind_laddr_v4(connp, NULL,
27153 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27154 	} else {
27155 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27156 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27157 	}
27158 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27159 }
27160 
27161 void
27162 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27163 {
27164 	conn_t  *connp = (conn_t *)proto_handle;
27165 	tcp_t	*tcp = connp->conn_tcp;
27166 	mblk_t *mp;
27167 	int error;
27168 
27169 	ASSERT(connp->conn_upper_handle != NULL);
27170 
27171 	/*
27172 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
27173 	 * is currently running.
27174 	 */
27175 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27176 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
27177 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
27178 		return;
27179 	}
27180 	tcp->tcp_rsrv_mp = NULL;
27181 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27182 
27183 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
27184 	ASSERT(error == 0);
27185 
27186 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27187 	tcp->tcp_rsrv_mp = mp;
27188 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27189 
27190 	if (tcp->tcp_fused) {
27191 		tcp_fuse_backenable(tcp);
27192 	} else {
27193 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27194 		/*
27195 		 * Send back a window update immediately if TCP is above
27196 		 * ESTABLISHED state and the increase of the rcv window
27197 		 * that the other side knows is at least 1 MSS after flow
27198 		 * control is lifted.
27199 		 */
27200 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27201 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
27202 			tcp_xmit_ctl(NULL, tcp,
27203 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27204 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27205 		}
27206 	}
27207 
27208 	squeue_synch_exit(connp->conn_sqp, connp);
27209 }
27210 
27211 /* ARGSUSED */
27212 int
27213 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27214     int mode, int32_t *rvalp, cred_t *cr)
27215 {
27216 	conn_t  	*connp = (conn_t *)proto_handle;
27217 	int		error;
27218 
27219 	ASSERT(connp->conn_upper_handle != NULL);
27220 
27221 	/* All Solaris components should pass a cred for this operation. */
27222 	ASSERT(cr != NULL);
27223 
27224 	switch (cmd) {
27225 		case ND_SET:
27226 		case ND_GET:
27227 		case TCP_IOC_DEFAULT_Q:
27228 		case _SIOCSOCKFALLBACK:
27229 		case TCP_IOC_ABORT_CONN:
27230 		case TI_GETPEERNAME:
27231 		case TI_GETMYNAME:
27232 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27233 			    cmd));
27234 			error = EINVAL;
27235 			break;
27236 		default:
27237 			/*
27238 			 * Pass on to IP using helper stream
27239 			 */
27240 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
27241 			    cmd, arg, mode, cr, rvalp);
27242 			break;
27243 	}
27244 	return (error);
27245 }
27246 
27247 sock_downcalls_t sock_tcp_downcalls = {
27248 	tcp_activate,
27249 	tcp_accept,
27250 	tcp_bind,
27251 	tcp_listen,
27252 	tcp_connect,
27253 	tcp_getpeername,
27254 	tcp_getsockname,
27255 	tcp_getsockopt,
27256 	tcp_setsockopt,
27257 	tcp_sendmsg,
27258 	NULL,
27259 	NULL,
27260 	NULL,
27261 	tcp_shutdown,
27262 	tcp_clr_flowctrl,
27263 	tcp_ioctl,
27264 	tcp_close,
27265 };
27266