xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision b24ab6762772a3f6a89393947930c7fa61306783)
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 	SOCK_CONNID_BUMP(eager->tcp_connid);
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;
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) {
16901 		if (tcp->tcp_ipversion == IPV4_VERSION &&
16902 		    !ipst->ips_ip4_observe.he_interested) {
16903 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
16904 			    &tcp->tcp_saved_tcph);
16905 		} else if (tcp->tcp_ipversion == IPV6_VERSION &&
16906 		    !ipst->ips_ip6_observe.he_interested) {
16907 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
16908 			    &tcp->tcp_saved_tcph);
16909 		}
16910 	}
16911 	/* Bypass tcp protocol for fused tcp loopback */
16912 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
16913 		return;
16914 
16915 	mss = tcp->tcp_mss;
16916 	if (tcp->tcp_xmit_zc_clean)
16917 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16918 
16919 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16920 	len = (int)(mp->b_wptr - mp->b_rptr);
16921 
16922 	/*
16923 	 * Criteria for fast path:
16924 	 *
16925 	 *   1. no unsent data
16926 	 *   2. single mblk in request
16927 	 *   3. connection established
16928 	 *   4. data in mblk
16929 	 *   5. len <= mss
16930 	 *   6. no tcp_valid bits
16931 	 */
16932 	if ((tcp->tcp_unsent != 0) ||
16933 	    (tcp->tcp_cork) ||
16934 	    (mp->b_cont != NULL) ||
16935 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16936 	    (len == 0) ||
16937 	    (len > mss) ||
16938 	    (tcp->tcp_valid_bits != 0)) {
16939 		tcp_wput_data(tcp, mp, B_FALSE);
16940 		return;
16941 	}
16942 
16943 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16944 	ASSERT(tcp->tcp_fin_sent == 0);
16945 
16946 	/* queue new packet onto retransmission queue */
16947 	if (tcp->tcp_xmit_head == NULL) {
16948 		tcp->tcp_xmit_head = mp;
16949 	} else {
16950 		tcp->tcp_xmit_last->b_cont = mp;
16951 	}
16952 	tcp->tcp_xmit_last = mp;
16953 	tcp->tcp_xmit_tail = mp;
16954 
16955 	/* find out how much we can send */
16956 	/* BEGIN CSTYLED */
16957 	/*
16958 	 *    un-acked	   usable
16959 	 *  |--------------|-----------------|
16960 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
16961 	 */
16962 	/* END CSTYLED */
16963 
16964 	/* start sending from tcp_snxt */
16965 	snxt = tcp->tcp_snxt;
16966 
16967 	/*
16968 	 * Check to see if this connection has been idled for some
16969 	 * time and no ACK is expected.  If it is, we need to slow
16970 	 * start again to get back the connection's "self-clock" as
16971 	 * described in VJ's paper.
16972 	 *
16973 	 * Refer to the comment in tcp_mss_set() for the calculation
16974 	 * of tcp_cwnd after idle.
16975 	 */
16976 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16977 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16978 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
16979 	}
16980 
16981 	usable = tcp->tcp_swnd;		/* tcp window size */
16982 	if (usable > tcp->tcp_cwnd)
16983 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16984 	usable -= snxt;		/* subtract stuff already sent */
16985 	suna = tcp->tcp_suna;
16986 	usable += suna;
16987 	/* usable can be < 0 if the congestion window is smaller */
16988 	if (len > usable) {
16989 		/* Can't send complete M_DATA in one shot */
16990 		goto slow;
16991 	}
16992 
16993 	mutex_enter(&tcp->tcp_non_sq_lock);
16994 	if (tcp->tcp_flow_stopped &&
16995 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16996 		tcp_clrqfull(tcp);
16997 	}
16998 	mutex_exit(&tcp->tcp_non_sq_lock);
16999 
17000 	/*
17001 	 * determine if anything to send (Nagle).
17002 	 *
17003 	 *   1. len < tcp_mss (i.e. small)
17004 	 *   2. unacknowledged data present
17005 	 *   3. len < nagle limit
17006 	 *   4. last packet sent < nagle limit (previous packet sent)
17007 	 */
17008 	if ((len < mss) && (snxt != suna) &&
17009 	    (len < (int)tcp->tcp_naglim) &&
17010 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17011 		/*
17012 		 * This was the first unsent packet and normally
17013 		 * mss < xmit_hiwater so there is no need to worry
17014 		 * about flow control. The next packet will go
17015 		 * through the flow control check in tcp_wput_data().
17016 		 */
17017 		/* leftover work from above */
17018 		tcp->tcp_unsent = len;
17019 		tcp->tcp_xmit_tail_unsent = len;
17020 
17021 		return;
17022 	}
17023 
17024 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17025 
17026 	if (snxt == suna) {
17027 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17028 	}
17029 
17030 	/* we have always sent something */
17031 	tcp->tcp_rack_cnt = 0;
17032 
17033 	tcp->tcp_snxt = snxt + len;
17034 	tcp->tcp_rack = tcp->tcp_rnxt;
17035 
17036 	if ((mp1 = dupb(mp)) == 0)
17037 		goto no_memory;
17038 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17039 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17040 
17041 	/* adjust tcp header information */
17042 	tcph = tcp->tcp_tcph;
17043 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17044 
17045 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17046 	sum = (sum >> 16) + (sum & 0xFFFF);
17047 	U16_TO_ABE16(sum, tcph->th_sum);
17048 
17049 	U32_TO_ABE32(snxt, tcph->th_seq);
17050 
17051 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17052 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17053 	BUMP_LOCAL(tcp->tcp_obsegs);
17054 
17055 	/* Update the latest receive window size in TCP header. */
17056 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17057 	    tcph->th_win);
17058 
17059 	tcp->tcp_last_sent_len = (ushort_t)len;
17060 
17061 	plen = len + tcp->tcp_hdr_len;
17062 
17063 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17064 		tcp->tcp_ipha->ipha_length = htons(plen);
17065 	} else {
17066 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17067 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17068 	}
17069 
17070 	/* see if we need to allocate a mblk for the headers */
17071 	hdrlen = tcp->tcp_hdr_len;
17072 	rptr = mp1->b_rptr - hdrlen;
17073 	db = mp1->b_datap;
17074 	if ((db->db_ref != 2) || rptr < db->db_base ||
17075 	    (!OK_32PTR(rptr))) {
17076 		/* NOTE: we assume allocb returns an OK_32PTR */
17077 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17078 		    tcps->tcps_wroff_xtra, BPRI_MED);
17079 		if (!mp) {
17080 			freemsg(mp1);
17081 			goto no_memory;
17082 		}
17083 		mp->b_cont = mp1;
17084 		mp1 = mp;
17085 		/* Leave room for Link Level header */
17086 		/* hdrlen = tcp->tcp_hdr_len; */
17087 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17088 		mp1->b_wptr = &rptr[hdrlen];
17089 	}
17090 	mp1->b_rptr = rptr;
17091 
17092 	/* Fill in the timestamp option. */
17093 	if (tcp->tcp_snd_ts_ok) {
17094 		U32_TO_BE32((uint32_t)lbolt,
17095 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17096 		U32_TO_BE32(tcp->tcp_ts_recent,
17097 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17098 	} else {
17099 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17100 	}
17101 
17102 	/* copy header into outgoing packet */
17103 	dst = (ipaddr_t *)rptr;
17104 	src = (ipaddr_t *)tcp->tcp_iphc;
17105 	dst[0] = src[0];
17106 	dst[1] = src[1];
17107 	dst[2] = src[2];
17108 	dst[3] = src[3];
17109 	dst[4] = src[4];
17110 	dst[5] = src[5];
17111 	dst[6] = src[6];
17112 	dst[7] = src[7];
17113 	dst[8] = src[8];
17114 	dst[9] = src[9];
17115 	if (hdrlen -= 40) {
17116 		hdrlen >>= 2;
17117 		dst += 10;
17118 		src += 10;
17119 		do {
17120 			*dst++ = *src++;
17121 		} while (--hdrlen);
17122 	}
17123 
17124 	/*
17125 	 * Set the ECN info in the TCP header.  Note that this
17126 	 * is not the template header.
17127 	 */
17128 	if (tcp->tcp_ecn_ok) {
17129 		SET_ECT(tcp, rptr);
17130 
17131 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17132 		if (tcp->tcp_ecn_echo_on)
17133 			tcph->th_flags[0] |= TH_ECE;
17134 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17135 			tcph->th_flags[0] |= TH_CWR;
17136 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17137 		}
17138 	}
17139 
17140 	if (tcp->tcp_ip_forward_progress) {
17141 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17142 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17143 		tcp->tcp_ip_forward_progress = B_FALSE;
17144 	}
17145 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17146 	return;
17147 
17148 	/*
17149 	 * If we ran out of memory, we pretend to have sent the packet
17150 	 * and that it was lost on the wire.
17151 	 */
17152 no_memory:
17153 	return;
17154 
17155 slow:
17156 	/* leftover work from above */
17157 	tcp->tcp_unsent = len;
17158 	tcp->tcp_xmit_tail_unsent = len;
17159 	tcp_wput_data(tcp, NULL, B_FALSE);
17160 }
17161 
17162 /* ARGSUSED */
17163 void
17164 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17165 {
17166 	conn_t			*connp = (conn_t *)arg;
17167 	tcp_t			*tcp = connp->conn_tcp;
17168 	queue_t			*q = tcp->tcp_rq;
17169 	struct tcp_options	*tcpopt;
17170 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17171 
17172 	/* socket options */
17173 	uint_t 			sopp_flags;
17174 	ssize_t			sopp_rxhiwat;
17175 	ssize_t			sopp_maxblk;
17176 	ushort_t		sopp_wroff;
17177 	ushort_t		sopp_tail;
17178 	ushort_t		sopp_copyopt;
17179 
17180 	tcpopt = (struct tcp_options *)mp->b_rptr;
17181 
17182 	/*
17183 	 * Drop the eager's ref on the listener, that was placed when
17184 	 * this eager began life in tcp_conn_request.
17185 	 */
17186 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17187 	if (IPCL_IS_NONSTR(connp)) {
17188 		/* Safe to free conn_ind message */
17189 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17190 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17191 	}
17192 
17193 	tcp->tcp_detached = B_FALSE;
17194 
17195 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17196 		/*
17197 		 * Someone blewoff the eager before we could finish
17198 		 * the accept.
17199 		 *
17200 		 * The only reason eager exists it because we put in
17201 		 * a ref on it when conn ind went up. We need to send
17202 		 * a disconnect indication up while the last reference
17203 		 * on the eager will be dropped by the squeue when we
17204 		 * return.
17205 		 */
17206 		ASSERT(tcp->tcp_listener == NULL);
17207 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17208 			if (IPCL_IS_NONSTR(connp)) {
17209 				ASSERT(tcp->tcp_issocket);
17210 				(*connp->conn_upcalls->su_disconnected)(
17211 				    connp->conn_upper_handle, tcp->tcp_connid,
17212 				    ECONNREFUSED);
17213 				freemsg(mp);
17214 			} else {
17215 				struct	T_discon_ind	*tdi;
17216 
17217 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17218 				/*
17219 				 * Let us reuse the incoming mblk to avoid
17220 				 * memory allocation failure problems. We know
17221 				 * that the size of the incoming mblk i.e.
17222 				 * stroptions is greater than sizeof
17223 				 * T_discon_ind. So the reallocb below can't
17224 				 * fail.
17225 				 */
17226 				freemsg(mp->b_cont);
17227 				mp->b_cont = NULL;
17228 				ASSERT(DB_REF(mp) == 1);
17229 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17230 				    B_FALSE);
17231 				ASSERT(mp != NULL);
17232 				DB_TYPE(mp) = M_PROTO;
17233 				((union T_primitives *)mp->b_rptr)->type =
17234 				    T_DISCON_IND;
17235 				tdi = (struct T_discon_ind *)mp->b_rptr;
17236 				if (tcp->tcp_issocket) {
17237 					tdi->DISCON_reason = ECONNREFUSED;
17238 					tdi->SEQ_number = 0;
17239 				} else {
17240 					tdi->DISCON_reason = ENOPROTOOPT;
17241 					tdi->SEQ_number =
17242 					    tcp->tcp_conn_req_seqnum;
17243 				}
17244 				mp->b_wptr = mp->b_rptr +
17245 				    sizeof (struct T_discon_ind);
17246 				putnext(q, mp);
17247 				return;
17248 			}
17249 		}
17250 		if (tcp->tcp_hard_binding) {
17251 			tcp->tcp_hard_binding = B_FALSE;
17252 			tcp->tcp_hard_bound = B_TRUE;
17253 		}
17254 		return;
17255 	}
17256 
17257 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17258 		int boundif = tcpopt->to_boundif;
17259 		uint_t len = sizeof (int);
17260 
17261 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17262 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17263 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred, NULL);
17264 	}
17265 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17266 		uint_t on = 1;
17267 		uint_t len = sizeof (uint_t);
17268 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17269 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17270 		    (uchar_t *)&on, NULL, tcp->tcp_cred, NULL);
17271 	}
17272 
17273 	/*
17274 	 * Set max window size (tcp_recv_hiwater) of the acceptor.
17275 	 */
17276 	if (tcp->tcp_rcv_list == NULL) {
17277 		/*
17278 		 * Recv queue is empty, tcp_rwnd should not have changed.
17279 		 * That means it should be equal to the listener's tcp_rwnd.
17280 		 */
17281 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
17282 	} else {
17283 #ifdef DEBUG
17284 		mblk_t *tmp;
17285 		mblk_t	*mp1;
17286 		uint_t	cnt = 0;
17287 
17288 		mp1 = tcp->tcp_rcv_list;
17289 		while ((tmp = mp1) != NULL) {
17290 			mp1 = tmp->b_next;
17291 			cnt += msgdsize(tmp);
17292 		}
17293 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17294 #endif
17295 		/* There is some data, add them back to get the max. */
17296 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17297 	}
17298 	/*
17299 	 * This is the first time we run on the correct
17300 	 * queue after tcp_accept. So fix all the q parameters
17301 	 * here.
17302 	 */
17303 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
17304 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17305 
17306 	sopp_rxhiwat = tcp->tcp_fused ?
17307 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
17308 	    tcp->tcp_recv_hiwater;
17309 
17310 	/*
17311 	 * Determine what write offset value to use depending on SACK and
17312 	 * whether the endpoint is fused or not.
17313 	 */
17314 	if (tcp->tcp_fused) {
17315 		ASSERT(tcp->tcp_loopback);
17316 		ASSERT(tcp->tcp_loopback_peer != NULL);
17317 		/*
17318 		 * For fused tcp loopback, set the stream head's write
17319 		 * offset value to zero since we won't be needing any room
17320 		 * for TCP/IP headers.  This would also improve performance
17321 		 * since it would reduce the amount of work done by kmem.
17322 		 * Non-fused tcp loopback case is handled separately below.
17323 		 */
17324 		sopp_wroff = 0;
17325 		/*
17326 		 * Update the peer's transmit parameters according to
17327 		 * our recently calculated high water mark value.
17328 		 */
17329 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17330 	} else if (tcp->tcp_snd_sack_ok) {
17331 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17332 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17333 	} else {
17334 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17335 		    tcps->tcps_wroff_xtra);
17336 	}
17337 
17338 	/*
17339 	 * If this is endpoint is handling SSL, then reserve extra
17340 	 * offset and space at the end.
17341 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17342 	 * overriding the previous setting. The extra cost of signing and
17343 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17344 	 * instead of a single contiguous one by the stream head
17345 	 * largely outweighs the statistical reduction of ACKs, when
17346 	 * applicable. The peer will also save on decryption and verification
17347 	 * costs.
17348 	 */
17349 	if (tcp->tcp_kssl_ctx != NULL) {
17350 		sopp_wroff += SSL3_WROFFSET;
17351 
17352 		sopp_flags |= SOCKOPT_TAIL;
17353 		sopp_tail = SSL3_MAX_TAIL_LEN;
17354 
17355 		sopp_flags |= SOCKOPT_ZCOPY;
17356 		sopp_copyopt = ZCVMUNSAFE;
17357 
17358 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
17359 	}
17360 
17361 	/* Send the options up */
17362 	if (IPCL_IS_NONSTR(connp)) {
17363 		struct sock_proto_props sopp;
17364 
17365 		sopp.sopp_flags = sopp_flags;
17366 		sopp.sopp_wroff = sopp_wroff;
17367 		sopp.sopp_maxblk = sopp_maxblk;
17368 		sopp.sopp_rxhiwat = sopp_rxhiwat;
17369 		if (sopp_flags & SOCKOPT_TAIL) {
17370 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17371 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
17372 			sopp.sopp_tail = sopp_tail;
17373 			sopp.sopp_zcopyflag = sopp_copyopt;
17374 		}
17375 		if (tcp->tcp_loopback) {
17376 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
17377 			sopp.sopp_loopback = B_TRUE;
17378 		}
17379 		(*connp->conn_upcalls->su_set_proto_props)
17380 		    (connp->conn_upper_handle, &sopp);
17381 	} else {
17382 		struct stroptions *stropt;
17383 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17384 		if (stropt_mp == NULL) {
17385 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
17386 			return;
17387 		}
17388 		DB_TYPE(stropt_mp) = M_SETOPTS;
17389 		stropt = (struct stroptions *)stropt_mp->b_rptr;
17390 		stropt_mp->b_wptr += sizeof (struct stroptions);
17391 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
17392 		stropt->so_hiwat = sopp_rxhiwat;
17393 		stropt->so_wroff = sopp_wroff;
17394 		stropt->so_maxblk = sopp_maxblk;
17395 
17396 		if (sopp_flags & SOCKOPT_TAIL) {
17397 			ASSERT(tcp->tcp_kssl_ctx != NULL);
17398 
17399 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
17400 			stropt->so_tail = sopp_tail;
17401 			stropt->so_copyopt = sopp_copyopt;
17402 		}
17403 
17404 		/* Send the options up */
17405 		putnext(q, stropt_mp);
17406 	}
17407 
17408 	freemsg(mp);
17409 	/*
17410 	 * Pass up any data and/or a fin that has been received.
17411 	 *
17412 	 * Adjust receive window in case it had decreased
17413 	 * (because there is data <=> tcp_rcv_list != NULL)
17414 	 * while the connection was detached. Note that
17415 	 * in case the eager was flow-controlled, w/o this
17416 	 * code, the rwnd may never open up again!
17417 	 */
17418 	if (tcp->tcp_rcv_list != NULL) {
17419 		if (IPCL_IS_NONSTR(connp)) {
17420 			mblk_t *mp;
17421 			int space_left;
17422 			int error;
17423 			boolean_t push = B_TRUE;
17424 
17425 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
17426 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
17427 			    &push) >= 0) {
17428 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17429 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17430 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17431 					tcp_xmit_ctl(NULL,
17432 					    tcp, (tcp->tcp_swnd == 0) ?
17433 					    tcp->tcp_suna : tcp->tcp_snxt,
17434 					    tcp->tcp_rnxt, TH_ACK);
17435 				}
17436 			}
17437 			while ((mp = tcp->tcp_rcv_list) != NULL) {
17438 				push = B_TRUE;
17439 				tcp->tcp_rcv_list = mp->b_next;
17440 				mp->b_next = NULL;
17441 				space_left = (*connp->conn_upcalls->su_recv)
17442 				    (connp->conn_upper_handle, mp, msgdsize(mp),
17443 				    0, &error, &push);
17444 				if (space_left < 0) {
17445 					/*
17446 					 * We should never be in middle of a
17447 					 * fallback, the squeue guarantees that.
17448 					 */
17449 					ASSERT(error != EOPNOTSUPP);
17450 				}
17451 			}
17452 			tcp->tcp_rcv_last_head = NULL;
17453 			tcp->tcp_rcv_last_tail = NULL;
17454 			tcp->tcp_rcv_cnt = 0;
17455 		} else {
17456 			/* We drain directly in case of fused tcp loopback */
17457 
17458 			if (!tcp->tcp_fused && canputnext(q)) {
17459 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
17460 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17461 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
17462 					tcp_xmit_ctl(NULL,
17463 					    tcp, (tcp->tcp_swnd == 0) ?
17464 					    tcp->tcp_suna : tcp->tcp_snxt,
17465 					    tcp->tcp_rnxt, TH_ACK);
17466 				}
17467 			}
17468 
17469 			(void) tcp_rcv_drain(tcp);
17470 		}
17471 
17472 		/*
17473 		 * For fused tcp loopback, back-enable peer endpoint
17474 		 * if it's currently flow-controlled.
17475 		 */
17476 		if (tcp->tcp_fused) {
17477 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17478 
17479 			ASSERT(peer_tcp != NULL);
17480 			ASSERT(peer_tcp->tcp_fused);
17481 
17482 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
17483 			if (peer_tcp->tcp_flow_stopped) {
17484 				tcp_clrqfull(peer_tcp);
17485 				TCP_STAT(tcps, tcp_fusion_backenabled);
17486 			}
17487 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
17488 		}
17489 	}
17490 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17491 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17492 		tcp->tcp_ordrel_done = B_TRUE;
17493 		if (IPCL_IS_NONSTR(connp)) {
17494 			ASSERT(tcp->tcp_ordrel_mp == NULL);
17495 			(*connp->conn_upcalls->su_opctl)(
17496 			    connp->conn_upper_handle,
17497 			    SOCK_OPCTL_SHUT_RECV, 0);
17498 		} else {
17499 			mp = tcp->tcp_ordrel_mp;
17500 			tcp->tcp_ordrel_mp = NULL;
17501 			putnext(q, mp);
17502 		}
17503 	}
17504 	if (tcp->tcp_hard_binding) {
17505 		tcp->tcp_hard_binding = B_FALSE;
17506 		tcp->tcp_hard_bound = B_TRUE;
17507 	}
17508 
17509 	if (tcp->tcp_ka_enabled) {
17510 		tcp->tcp_ka_last_intrvl = 0;
17511 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17512 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17513 	}
17514 
17515 	/*
17516 	 * At this point, eager is fully established and will
17517 	 * have the following references -
17518 	 *
17519 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17520 	 * 1 reference for the squeue which will be dropped by the squeue as
17521 	 *	soon as this function returns.
17522 	 * There will be 1 additonal reference for being in classifier
17523 	 *	hash list provided something bad hasn't happened.
17524 	 */
17525 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17526 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17527 }
17528 
17529 /*
17530  * The function called through squeue to get behind listener's perimeter to
17531  * send a deffered conn_ind.
17532  */
17533 /* ARGSUSED */
17534 void
17535 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17536 {
17537 	conn_t	*connp = (conn_t *)arg;
17538 	tcp_t *listener = connp->conn_tcp;
17539 	struct T_conn_ind *conn_ind;
17540 	tcp_t *tcp;
17541 
17542 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
17543 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17544 	    conn_ind->OPT_length);
17545 
17546 	if (listener->tcp_state != TCPS_LISTEN) {
17547 		/*
17548 		 * If listener has closed, it would have caused a
17549 		 * a cleanup/blowoff to happen for the eager, so
17550 		 * we don't need to do anything more.
17551 		 */
17552 		freemsg(mp);
17553 		return;
17554 	}
17555 
17556 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
17557 }
17558 
17559 /* ARGSUSED */
17560 static int
17561 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
17562 {
17563 	tcp_t *listener, *eager;
17564 	mblk_t *opt_mp;
17565 	struct tcp_options *tcpopt;
17566 
17567 	listener = lconnp->conn_tcp;
17568 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17569 	eager = econnp->conn_tcp;
17570 	ASSERT(eager->tcp_listener != NULL);
17571 
17572 	ASSERT(eager->tcp_rq != NULL);
17573 
17574 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
17575 	if (opt_mp == NULL) {
17576 		return (-TPROTO);
17577 	}
17578 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
17579 	eager->tcp_issocket = B_TRUE;
17580 
17581 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17582 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
17583 	ASSERT(econnp->conn_netstack ==
17584 	    listener->tcp_connp->conn_netstack);
17585 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
17586 
17587 	/* Put the ref for IP */
17588 	CONN_INC_REF(econnp);
17589 
17590 	/*
17591 	 * We should have minimum of 3 references on the conn
17592 	 * at this point. One each for TCP and IP and one for
17593 	 * the T_conn_ind that was sent up when the 3-way handshake
17594 	 * completed. In the normal case we would also have another
17595 	 * reference (making a total of 4) for the conn being in the
17596 	 * classifier hash list. However the eager could have received
17597 	 * an RST subsequently and tcp_closei_local could have removed
17598 	 * the eager from the classifier hash list, hence we can't
17599 	 * assert that reference.
17600 	 */
17601 	ASSERT(econnp->conn_ref >= 3);
17602 
17603 	opt_mp->b_datap->db_type = M_SETOPTS;
17604 	opt_mp->b_wptr += sizeof (struct tcp_options);
17605 
17606 	/*
17607 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17608 	 * from listener to acceptor.
17609 	 */
17610 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
17611 	tcpopt->to_flags = 0;
17612 
17613 	if (listener->tcp_bound_if != 0) {
17614 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
17615 		tcpopt->to_boundif = listener->tcp_bound_if;
17616 	}
17617 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17618 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
17619 	}
17620 
17621 	mutex_enter(&listener->tcp_eager_lock);
17622 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17623 
17624 		tcp_t *tail;
17625 		tcp_t *tcp;
17626 		mblk_t *mp1;
17627 
17628 		tcp = listener->tcp_eager_prev_q0;
17629 		/*
17630 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
17631 		 * deferred T_conn_ind queue. We need to get to the head
17632 		 * of the queue in order to send up T_conn_ind the same
17633 		 * order as how the 3WHS is completed.
17634 		 */
17635 		while (tcp != listener) {
17636 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17637 			    !tcp->tcp_kssl_pending)
17638 				break;
17639 			else
17640 				tcp = tcp->tcp_eager_prev_q0;
17641 		}
17642 		/* None of the pending eagers can be sent up now */
17643 		if (tcp == listener)
17644 			goto no_more_eagers;
17645 
17646 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17647 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17648 		/* Move from q0 to q */
17649 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17650 		listener->tcp_conn_req_cnt_q0--;
17651 		listener->tcp_conn_req_cnt_q++;
17652 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17653 		    tcp->tcp_eager_prev_q0;
17654 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17655 		    tcp->tcp_eager_next_q0;
17656 		tcp->tcp_eager_prev_q0 = NULL;
17657 		tcp->tcp_eager_next_q0 = NULL;
17658 		tcp->tcp_conn_def_q0 = B_FALSE;
17659 
17660 		/* Make sure the tcp isn't in the list of droppables */
17661 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
17662 		    tcp->tcp_eager_prev_drop_q0 == NULL);
17663 
17664 		/*
17665 		 * Insert at end of the queue because sockfs sends
17666 		 * down T_CONN_RES in chronological order. Leaving
17667 		 * the older conn indications at front of the queue
17668 		 * helps reducing search time.
17669 		 */
17670 		tail = listener->tcp_eager_last_q;
17671 		if (tail != NULL) {
17672 			tail->tcp_eager_next_q = tcp;
17673 		} else {
17674 			listener->tcp_eager_next_q = tcp;
17675 		}
17676 		listener->tcp_eager_last_q = tcp;
17677 		tcp->tcp_eager_next_q = NULL;
17678 
17679 		/* Need to get inside the listener perimeter */
17680 		CONN_INC_REF(listener->tcp_connp);
17681 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
17682 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
17683 		    SQTAG_TCP_SEND_PENDING);
17684 	}
17685 no_more_eagers:
17686 	tcp_eager_unlink(eager);
17687 	mutex_exit(&listener->tcp_eager_lock);
17688 
17689 	/*
17690 	 * At this point, the eager is detached from the listener
17691 	 * but we still have an extra refs on eager (apart from the
17692 	 * usual tcp references). The ref was placed in tcp_rput_data
17693 	 * before sending the conn_ind in tcp_send_conn_ind.
17694 	 * The ref will be dropped in tcp_accept_finish().
17695 	 */
17696 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
17697 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
17698 	return (0);
17699 }
17700 
17701 int
17702 tcp_accept(sock_lower_handle_t lproto_handle,
17703     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
17704     cred_t *cr)
17705 {
17706 	conn_t *lconnp, *econnp;
17707 	tcp_t *listener, *eager;
17708 	tcp_stack_t	*tcps;
17709 
17710 	lconnp = (conn_t *)lproto_handle;
17711 	listener = lconnp->conn_tcp;
17712 	ASSERT(listener->tcp_state == TCPS_LISTEN);
17713 	econnp = (conn_t *)eproto_handle;
17714 	eager = econnp->conn_tcp;
17715 	ASSERT(eager->tcp_listener != NULL);
17716 	tcps = eager->tcp_tcps;
17717 
17718 	/*
17719 	 * It is OK to manipulate these fields outside the eager's squeue
17720 	 * because they will not start being used until tcp_accept_finish
17721 	 * has been called.
17722 	 */
17723 	ASSERT(lconnp->conn_upper_handle != NULL);
17724 	ASSERT(econnp->conn_upper_handle == NULL);
17725 	econnp->conn_upper_handle = sock_handle;
17726 	econnp->conn_upcalls = lconnp->conn_upcalls;
17727 	ASSERT(IPCL_IS_NONSTR(econnp));
17728 	/*
17729 	 * Create helper stream if it is a non-TPI TCP connection.
17730 	 */
17731 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
17732 		ip1dbg(("tcp_accept: create of IP helper stream"
17733 		    " failed\n"));
17734 		return (EPROTO);
17735 	}
17736 	eager->tcp_rq = econnp->conn_rq;
17737 	eager->tcp_wq = econnp->conn_wq;
17738 
17739 	ASSERT(eager->tcp_rq != NULL);
17740 
17741 	return (tcp_accept_common(lconnp, econnp, cr));
17742 }
17743 
17744 
17745 /*
17746  * This is the STREAMS entry point for T_CONN_RES coming down on
17747  * Acceptor STREAM when  sockfs listener does accept processing.
17748  * Read the block comment on top of tcp_conn_request().
17749  */
17750 void
17751 tcp_tpi_accept(queue_t *q, mblk_t *mp)
17752 {
17753 	queue_t *rq = RD(q);
17754 	struct T_conn_res *conn_res;
17755 	tcp_t *eager;
17756 	tcp_t *listener;
17757 	struct T_ok_ack *ok;
17758 	t_scalar_t PRIM_type;
17759 	conn_t *econnp;
17760 	cred_t *cr;
17761 
17762 	ASSERT(DB_TYPE(mp) == M_PROTO);
17763 
17764 	/*
17765 	 * All Solaris components should pass a db_credp
17766 	 * for this TPI message, hence we ASSERT.
17767 	 * But in case there is some other M_PROTO that looks
17768 	 * like a TPI message sent by some other kernel
17769 	 * component, we check and return an error.
17770 	 */
17771 	cr = msg_getcred(mp, NULL);
17772 	ASSERT(cr != NULL);
17773 	if (cr == NULL) {
17774 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
17775 		if (mp != NULL)
17776 			putnext(rq, mp);
17777 		return;
17778 	}
17779 	conn_res = (struct T_conn_res *)mp->b_rptr;
17780 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17781 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17782 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17783 		if (mp != NULL)
17784 			putnext(rq, mp);
17785 		return;
17786 	}
17787 	switch (conn_res->PRIM_type) {
17788 	case O_T_CONN_RES:
17789 	case T_CONN_RES:
17790 		/*
17791 		 * We pass up an err ack if allocb fails. This will
17792 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17793 		 * tcp_eager_blowoff to be called. sockfs will then call
17794 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17795 		 * we need to do the allocb up here because we have to
17796 		 * make sure rq->q_qinfo->qi_qclose still points to the
17797 		 * correct function (tcp_tpi_close_accept) in case allocb
17798 		 * fails.
17799 		 */
17800 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17801 		    &eager, conn_res->OPT_length);
17802 		PRIM_type = conn_res->PRIM_type;
17803 		mp->b_datap->db_type = M_PCPROTO;
17804 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17805 		ok = (struct T_ok_ack *)mp->b_rptr;
17806 		ok->PRIM_type = T_OK_ACK;
17807 		ok->CORRECT_prim = PRIM_type;
17808 		econnp = eager->tcp_connp;
17809 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
17810 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
17811 		eager->tcp_rq = rq;
17812 		eager->tcp_wq = q;
17813 		rq->q_ptr = econnp;
17814 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
17815 		q->q_ptr = econnp;
17816 		q->q_qinfo = &tcp_winit;
17817 		listener = eager->tcp_listener;
17818 
17819 		if (tcp_accept_common(listener->tcp_connp,
17820 		    econnp, cr) < 0) {
17821 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17822 			if (mp != NULL)
17823 				putnext(rq, mp);
17824 			return;
17825 		}
17826 
17827 		/*
17828 		 * Send the new local address also up to sockfs. There
17829 		 * should already be enough space in the mp that came
17830 		 * down from soaccept().
17831 		 */
17832 		if (eager->tcp_family == AF_INET) {
17833 			sin_t *sin;
17834 
17835 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17836 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17837 			sin = (sin_t *)mp->b_wptr;
17838 			mp->b_wptr += sizeof (sin_t);
17839 			sin->sin_family = AF_INET;
17840 			sin->sin_port = eager->tcp_lport;
17841 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17842 		} else {
17843 			sin6_t *sin6;
17844 
17845 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17846 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17847 			sin6 = (sin6_t *)mp->b_wptr;
17848 			mp->b_wptr += sizeof (sin6_t);
17849 			sin6->sin6_family = AF_INET6;
17850 			sin6->sin6_port = eager->tcp_lport;
17851 			if (eager->tcp_ipversion == IPV4_VERSION) {
17852 				sin6->sin6_flowinfo = 0;
17853 				IN6_IPADDR_TO_V4MAPPED(
17854 				    eager->tcp_ipha->ipha_src,
17855 				    &sin6->sin6_addr);
17856 			} else {
17857 				ASSERT(eager->tcp_ip6h != NULL);
17858 				sin6->sin6_flowinfo =
17859 				    eager->tcp_ip6h->ip6_vcf &
17860 				    ~IPV6_VERS_AND_FLOW_MASK;
17861 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17862 			}
17863 			sin6->sin6_scope_id = 0;
17864 			sin6->__sin6_src_id = 0;
17865 		}
17866 
17867 		putnext(rq, mp);
17868 		return;
17869 	default:
17870 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17871 		if (mp != NULL)
17872 			putnext(rq, mp);
17873 		return;
17874 	}
17875 }
17876 
17877 static int
17878 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17879 {
17880 	sin_t *sin = (sin_t *)sa;
17881 	sin6_t *sin6 = (sin6_t *)sa;
17882 
17883 	switch (tcp->tcp_family) {
17884 	case AF_INET:
17885 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17886 
17887 		if (*salenp < sizeof (sin_t))
17888 			return (EINVAL);
17889 
17890 		*sin = sin_null;
17891 		sin->sin_family = AF_INET;
17892 		if (tcp->tcp_state >= TCPS_BOUND) {
17893 			sin->sin_port = tcp->tcp_lport;
17894 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
17895 		}
17896 		*salenp = sizeof (sin_t);
17897 		break;
17898 
17899 	case AF_INET6:
17900 		if (*salenp < sizeof (sin6_t))
17901 			return (EINVAL);
17902 
17903 		*sin6 = sin6_null;
17904 		sin6->sin6_family = AF_INET6;
17905 		if (tcp->tcp_state >= TCPS_BOUND) {
17906 			sin6->sin6_port = tcp->tcp_lport;
17907 			mutex_enter(&tcp->tcp_connp->conn_lock);
17908 			if (tcp->tcp_ipversion == IPV4_VERSION) {
17909 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
17910 				    &sin6->sin6_addr);
17911 			} else {
17912 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
17913 			}
17914 			mutex_exit(&tcp->tcp_connp->conn_lock);
17915 		}
17916 		*salenp = sizeof (sin6_t);
17917 		break;
17918 	}
17919 
17920 	return (0);
17921 }
17922 
17923 static int
17924 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
17925 {
17926 	sin_t *sin = (sin_t *)sa;
17927 	sin6_t *sin6 = (sin6_t *)sa;
17928 
17929 	if (tcp->tcp_state < TCPS_SYN_RCVD)
17930 		return (ENOTCONN);
17931 
17932 	switch (tcp->tcp_family) {
17933 	case AF_INET:
17934 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
17935 
17936 		if (*salenp < sizeof (sin_t))
17937 			return (EINVAL);
17938 
17939 		*sin = sin_null;
17940 		sin->sin_family = AF_INET;
17941 		sin->sin_port = tcp->tcp_fport;
17942 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
17943 		    sin->sin_addr.s_addr);
17944 		*salenp = sizeof (sin_t);
17945 		break;
17946 
17947 	case AF_INET6:
17948 		if (*salenp < sizeof (sin6_t))
17949 			return (EINVAL);
17950 
17951 		*sin6 = sin6_null;
17952 		sin6->sin6_family = AF_INET6;
17953 		sin6->sin6_port = tcp->tcp_fport;
17954 		sin6->sin6_addr = tcp->tcp_remote_v6;
17955 		mutex_enter(&tcp->tcp_connp->conn_lock);
17956 		if (tcp->tcp_ipversion == IPV6_VERSION) {
17957 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
17958 			    ~IPV6_VERS_AND_FLOW_MASK;
17959 		}
17960 		mutex_exit(&tcp->tcp_connp->conn_lock);
17961 		*salenp = sizeof (sin6_t);
17962 		break;
17963 	}
17964 
17965 	return (0);
17966 }
17967 
17968 /*
17969  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
17970  */
17971 static void
17972 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
17973 {
17974 	void	*data;
17975 	mblk_t	*datamp = mp->b_cont;
17976 	tcp_t	*tcp = Q_TO_TCP(q);
17977 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
17978 
17979 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
17980 		cmdp->cb_error = EPROTO;
17981 		qreply(q, mp);
17982 		return;
17983 	}
17984 
17985 	data = datamp->b_rptr;
17986 
17987 	switch (cmdp->cb_cmd) {
17988 	case TI_GETPEERNAME:
17989 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
17990 		break;
17991 	case TI_GETMYNAME:
17992 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
17993 		break;
17994 	default:
17995 		cmdp->cb_error = EINVAL;
17996 		break;
17997 	}
17998 
17999 	qreply(q, mp);
18000 }
18001 
18002 void
18003 tcp_wput(queue_t *q, mblk_t *mp)
18004 {
18005 	conn_t	*connp = Q_TO_CONN(q);
18006 	tcp_t	*tcp;
18007 	void (*output_proc)();
18008 	t_scalar_t type;
18009 	uchar_t *rptr;
18010 	struct iocblk	*iocp;
18011 	size_t size;
18012 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18013 
18014 	ASSERT(connp->conn_ref >= 2);
18015 
18016 	switch (DB_TYPE(mp)) {
18017 	case M_DATA:
18018 		tcp = connp->conn_tcp;
18019 		ASSERT(tcp != NULL);
18020 
18021 		size = msgdsize(mp);
18022 
18023 		mutex_enter(&tcp->tcp_non_sq_lock);
18024 		tcp->tcp_squeue_bytes += size;
18025 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18026 			tcp_setqfull(tcp);
18027 		}
18028 		mutex_exit(&tcp->tcp_non_sq_lock);
18029 
18030 		CONN_INC_REF(connp);
18031 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18032 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18033 		return;
18034 
18035 	case M_CMD:
18036 		tcp_wput_cmdblk(q, mp);
18037 		return;
18038 
18039 	case M_PROTO:
18040 	case M_PCPROTO:
18041 		/*
18042 		 * if it is a snmp message, don't get behind the squeue
18043 		 */
18044 		tcp = connp->conn_tcp;
18045 		rptr = mp->b_rptr;
18046 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18047 			type = ((union T_primitives *)rptr)->type;
18048 		} else {
18049 			if (tcp->tcp_debug) {
18050 				(void) strlog(TCP_MOD_ID, 0, 1,
18051 				    SL_ERROR|SL_TRACE,
18052 				    "tcp_wput_proto, dropping one...");
18053 			}
18054 			freemsg(mp);
18055 			return;
18056 		}
18057 		if (type == T_SVR4_OPTMGMT_REQ) {
18058 			/*
18059 			 * All Solaris components should pass a db_credp
18060 			 * for this TPI message, hence we ASSERT.
18061 			 * But in case there is some other M_PROTO that looks
18062 			 * like a TPI message sent by some other kernel
18063 			 * component, we check and return an error.
18064 			 */
18065 			cred_t	*cr = msg_getcred(mp, NULL);
18066 
18067 			ASSERT(cr != NULL);
18068 			if (cr == NULL) {
18069 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18070 				return;
18071 			}
18072 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18073 			    cr)) {
18074 				/*
18075 				 * This was a SNMP request
18076 				 */
18077 				return;
18078 			} else {
18079 				output_proc = tcp_wput_proto;
18080 			}
18081 		} else {
18082 			output_proc = tcp_wput_proto;
18083 		}
18084 		break;
18085 	case M_IOCTL:
18086 		/*
18087 		 * Most ioctls can be processed right away without going via
18088 		 * squeues - process them right here. Those that do require
18089 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18090 		 * are processed by tcp_wput_ioctl().
18091 		 */
18092 		iocp = (struct iocblk *)mp->b_rptr;
18093 		tcp = connp->conn_tcp;
18094 
18095 		switch (iocp->ioc_cmd) {
18096 		case TCP_IOC_ABORT_CONN:
18097 			tcp_ioctl_abort_conn(q, mp);
18098 			return;
18099 		case TI_GETPEERNAME:
18100 		case TI_GETMYNAME:
18101 			mi_copyin(q, mp, NULL,
18102 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18103 			return;
18104 		case ND_SET:
18105 			/* nd_getset does the necessary checks */
18106 		case ND_GET:
18107 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18108 				CALL_IP_WPUT(connp, q, mp);
18109 				return;
18110 			}
18111 			qreply(q, mp);
18112 			return;
18113 		case TCP_IOC_DEFAULT_Q:
18114 			/*
18115 			 * Wants to be the default wq. Check the credentials
18116 			 * first, the rest is executed via squeue.
18117 			 */
18118 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18119 				iocp->ioc_error = EPERM;
18120 				iocp->ioc_count = 0;
18121 				mp->b_datap->db_type = M_IOCACK;
18122 				qreply(q, mp);
18123 				return;
18124 			}
18125 			output_proc = tcp_wput_ioctl;
18126 			break;
18127 		default:
18128 			output_proc = tcp_wput_ioctl;
18129 			break;
18130 		}
18131 		break;
18132 	default:
18133 		output_proc = tcp_wput_nondata;
18134 		break;
18135 	}
18136 
18137 	CONN_INC_REF(connp);
18138 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18139 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18140 }
18141 
18142 /*
18143  * Initial STREAMS write side put() procedure for sockets. It tries to
18144  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18145  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18146  * are handled by tcp_wput() as usual.
18147  *
18148  * All further messages will also be handled by tcp_wput() because we cannot
18149  * be sure that the above short cut is safe later.
18150  */
18151 static void
18152 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18153 {
18154 	conn_t			*connp = Q_TO_CONN(wq);
18155 	tcp_t			*tcp = connp->conn_tcp;
18156 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18157 
18158 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18159 	wq->q_qinfo = &tcp_winit;
18160 
18161 	ASSERT(IPCL_IS_TCP(connp));
18162 	ASSERT(TCP_IS_SOCKET(tcp));
18163 
18164 	if (DB_TYPE(mp) == M_PCPROTO &&
18165 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18166 	    car->PRIM_type == T_CAPABILITY_REQ) {
18167 		tcp_capability_req(tcp, mp);
18168 		return;
18169 	}
18170 
18171 	tcp_wput(wq, mp);
18172 }
18173 
18174 /* ARGSUSED */
18175 static void
18176 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18177 {
18178 #ifdef DEBUG
18179 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18180 #endif
18181 	freemsg(mp);
18182 }
18183 
18184 static boolean_t
18185 tcp_zcopy_check(tcp_t *tcp)
18186 {
18187 	conn_t	*connp = tcp->tcp_connp;
18188 	ire_t	*ire;
18189 	boolean_t	zc_enabled = B_FALSE;
18190 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18191 
18192 	if (do_tcpzcopy == 2)
18193 		zc_enabled = B_TRUE;
18194 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18195 	    IPCL_IS_CONNECTED(connp) &&
18196 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18197 	    connp->conn_dontroute == 0 &&
18198 	    !connp->conn_nexthop_set &&
18199 	    connp->conn_outgoing_ill == NULL &&
18200 	    do_tcpzcopy == 1) {
18201 		/*
18202 		 * the checks above  closely resemble the fast path checks
18203 		 * in tcp_send_data().
18204 		 */
18205 		mutex_enter(&connp->conn_lock);
18206 		ire = connp->conn_ire_cache;
18207 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18208 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18209 			IRE_REFHOLD(ire);
18210 			if (ire->ire_stq != NULL) {
18211 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18212 
18213 				zc_enabled = ill && (ill->ill_capabilities &
18214 				    ILL_CAPAB_ZEROCOPY) &&
18215 				    (ill->ill_zerocopy_capab->
18216 				    ill_zerocopy_flags != 0);
18217 			}
18218 			IRE_REFRELE(ire);
18219 		}
18220 		mutex_exit(&connp->conn_lock);
18221 	}
18222 	tcp->tcp_snd_zcopy_on = zc_enabled;
18223 	if (!TCP_IS_DETACHED(tcp)) {
18224 		if (zc_enabled) {
18225 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18226 			    ZCVMSAFE);
18227 			TCP_STAT(tcps, tcp_zcopy_on);
18228 		} else {
18229 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
18230 			    ZCVMUNSAFE);
18231 			TCP_STAT(tcps, tcp_zcopy_off);
18232 		}
18233 	}
18234 	return (zc_enabled);
18235 }
18236 
18237 static mblk_t *
18238 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18239 {
18240 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18241 
18242 	if (do_tcpzcopy == 2)
18243 		return (bp);
18244 	else if (tcp->tcp_snd_zcopy_on) {
18245 		tcp->tcp_snd_zcopy_on = B_FALSE;
18246 		if (!TCP_IS_DETACHED(tcp)) {
18247 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
18248 			    ZCVMUNSAFE);
18249 			TCP_STAT(tcps, tcp_zcopy_disable);
18250 		}
18251 	}
18252 	return (tcp_zcopy_backoff(tcp, bp, 0));
18253 }
18254 
18255 /*
18256  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18257  * the original desballoca'ed segmapped mblk.
18258  */
18259 static mblk_t *
18260 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18261 {
18262 	mblk_t *head, *tail, *nbp;
18263 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18264 
18265 	if (IS_VMLOANED_MBLK(bp)) {
18266 		TCP_STAT(tcps, tcp_zcopy_backoff);
18267 		if ((head = copyb(bp)) == NULL) {
18268 			/* fail to backoff; leave it for the next backoff */
18269 			tcp->tcp_xmit_zc_clean = B_FALSE;
18270 			return (bp);
18271 		}
18272 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18273 			if (fix_xmitlist)
18274 				tcp_zcopy_notify(tcp);
18275 			else
18276 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18277 		}
18278 		nbp = bp->b_cont;
18279 		if (fix_xmitlist) {
18280 			head->b_prev = bp->b_prev;
18281 			head->b_next = bp->b_next;
18282 			if (tcp->tcp_xmit_tail == bp)
18283 				tcp->tcp_xmit_tail = head;
18284 		}
18285 		bp->b_next = NULL;
18286 		bp->b_prev = NULL;
18287 		freeb(bp);
18288 	} else {
18289 		head = bp;
18290 		nbp = bp->b_cont;
18291 	}
18292 	tail = head;
18293 	while (nbp) {
18294 		if (IS_VMLOANED_MBLK(nbp)) {
18295 			TCP_STAT(tcps, tcp_zcopy_backoff);
18296 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18297 				tcp->tcp_xmit_zc_clean = B_FALSE;
18298 				tail->b_cont = nbp;
18299 				return (head);
18300 			}
18301 			tail = tail->b_cont;
18302 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18303 				if (fix_xmitlist)
18304 					tcp_zcopy_notify(tcp);
18305 				else
18306 					tail->b_datap->db_struioflag |=
18307 					    STRUIO_ZCNOTIFY;
18308 			}
18309 			bp = nbp;
18310 			nbp = nbp->b_cont;
18311 			if (fix_xmitlist) {
18312 				tail->b_prev = bp->b_prev;
18313 				tail->b_next = bp->b_next;
18314 				if (tcp->tcp_xmit_tail == bp)
18315 					tcp->tcp_xmit_tail = tail;
18316 			}
18317 			bp->b_next = NULL;
18318 			bp->b_prev = NULL;
18319 			freeb(bp);
18320 		} else {
18321 			tail->b_cont = nbp;
18322 			tail = nbp;
18323 			nbp = nbp->b_cont;
18324 		}
18325 	}
18326 	if (fix_xmitlist) {
18327 		tcp->tcp_xmit_last = tail;
18328 		tcp->tcp_xmit_zc_clean = B_TRUE;
18329 	}
18330 	return (head);
18331 }
18332 
18333 static void
18334 tcp_zcopy_notify(tcp_t *tcp)
18335 {
18336 	struct stdata	*stp;
18337 	conn_t *connp;
18338 
18339 	if (tcp->tcp_detached)
18340 		return;
18341 	connp = tcp->tcp_connp;
18342 	if (IPCL_IS_NONSTR(connp)) {
18343 		(*connp->conn_upcalls->su_zcopy_notify)
18344 		    (connp->conn_upper_handle);
18345 		return;
18346 	}
18347 	stp = STREAM(tcp->tcp_rq);
18348 	mutex_enter(&stp->sd_lock);
18349 	stp->sd_flag |= STZCNOTIFY;
18350 	cv_broadcast(&stp->sd_zcopy_wait);
18351 	mutex_exit(&stp->sd_lock);
18352 }
18353 
18354 static boolean_t
18355 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18356 {
18357 	ire_t	*ire;
18358 	conn_t	*connp = tcp->tcp_connp;
18359 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18360 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18361 
18362 	mutex_enter(&connp->conn_lock);
18363 	ire = connp->conn_ire_cache;
18364 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18365 
18366 	if ((ire != NULL) &&
18367 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18368 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18369 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18370 		IRE_REFHOLD(ire);
18371 		mutex_exit(&connp->conn_lock);
18372 	} else {
18373 		boolean_t cached = B_FALSE;
18374 		ts_label_t *tsl;
18375 
18376 		/* force a recheck later on */
18377 		tcp->tcp_ire_ill_check_done = B_FALSE;
18378 
18379 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18380 		connp->conn_ire_cache = NULL;
18381 		mutex_exit(&connp->conn_lock);
18382 
18383 		if (ire != NULL)
18384 			IRE_REFRELE_NOTR(ire);
18385 
18386 		tsl = crgetlabel(CONN_CRED(connp));
18387 		ire = (dst ?
18388 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18389 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18390 		    connp->conn_zoneid, tsl, ipst));
18391 
18392 		if (ire == NULL) {
18393 			TCP_STAT(tcps, tcp_ire_null);
18394 			return (B_FALSE);
18395 		}
18396 
18397 		IRE_REFHOLD_NOTR(ire);
18398 
18399 		mutex_enter(&connp->conn_lock);
18400 		if (CONN_CACHE_IRE(connp)) {
18401 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18402 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18403 				TCP_CHECK_IREINFO(tcp, ire);
18404 				connp->conn_ire_cache = ire;
18405 				cached = B_TRUE;
18406 			}
18407 			rw_exit(&ire->ire_bucket->irb_lock);
18408 		}
18409 		mutex_exit(&connp->conn_lock);
18410 
18411 		/*
18412 		 * We can continue to use the ire but since it was
18413 		 * not cached, we should drop the extra reference.
18414 		 */
18415 		if (!cached)
18416 			IRE_REFRELE_NOTR(ire);
18417 
18418 		/*
18419 		 * Rampart note: no need to select a new label here, since
18420 		 * labels are not allowed to change during the life of a TCP
18421 		 * connection.
18422 		 */
18423 	}
18424 
18425 	*irep = ire;
18426 
18427 	return (B_TRUE);
18428 }
18429 
18430 /*
18431  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18432  *
18433  * 0 = success;
18434  * 1 = failed to find ire and ill.
18435  */
18436 static boolean_t
18437 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18438 {
18439 	ipha_t		*ipha;
18440 	ipaddr_t	dst;
18441 	ire_t		*ire;
18442 	ill_t		*ill;
18443 	mblk_t		*ire_fp_mp;
18444 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18445 
18446 	if (mp != NULL)
18447 		ipha = (ipha_t *)mp->b_rptr;
18448 	else
18449 		ipha = tcp->tcp_ipha;
18450 	dst = ipha->ipha_dst;
18451 
18452 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18453 		return (B_FALSE);
18454 
18455 	if ((ire->ire_flags & RTF_MULTIRT) ||
18456 	    (ire->ire_stq == NULL) ||
18457 	    (ire->ire_nce == NULL) ||
18458 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18459 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18460 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18461 		TCP_STAT(tcps, tcp_ip_ire_send);
18462 		IRE_REFRELE(ire);
18463 		return (B_FALSE);
18464 	}
18465 
18466 	ill = ire_to_ill(ire);
18467 	ASSERT(ill != NULL);
18468 
18469 	if (!tcp->tcp_ire_ill_check_done) {
18470 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18471 		tcp->tcp_ire_ill_check_done = B_TRUE;
18472 	}
18473 
18474 	*irep = ire;
18475 	*illp = ill;
18476 
18477 	return (B_TRUE);
18478 }
18479 
18480 static void
18481 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18482 {
18483 	ipha_t		*ipha;
18484 	ipaddr_t	src;
18485 	ipaddr_t	dst;
18486 	uint32_t	cksum;
18487 	ire_t		*ire;
18488 	uint16_t	*up;
18489 	ill_t		*ill;
18490 	conn_t		*connp = tcp->tcp_connp;
18491 	uint32_t	hcksum_txflags = 0;
18492 	mblk_t		*ire_fp_mp;
18493 	uint_t		ire_fp_mp_len;
18494 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18495 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18496 	cred_t		*cr;
18497 	pid_t		cpid;
18498 
18499 	ASSERT(DB_TYPE(mp) == M_DATA);
18500 
18501 	/*
18502 	 * Here we need to handle the overloading of the cred_t for
18503 	 * both getpeerucred and TX.
18504 	 * If this is a SYN then the caller already set db_credp so
18505 	 * that getpeerucred will work. But if TX is in use we might have
18506 	 * a conn_effective_cred which is different, and we need to use that
18507 	 * cred to make TX use the correct label and label dependent route.
18508 	 */
18509 	if (is_system_labeled()) {
18510 		cr = msg_getcred(mp, &cpid);
18511 		if (cr == NULL || connp->conn_effective_cred != NULL)
18512 			mblk_setcred(mp, CONN_CRED(connp), cpid);
18513 	}
18514 
18515 	ipha = (ipha_t *)mp->b_rptr;
18516 	src = ipha->ipha_src;
18517 	dst = ipha->ipha_dst;
18518 
18519 	ASSERT(q != NULL);
18520 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
18521 
18522 	/*
18523 	 * Drop off fast path for IPv6 and also if options are present or
18524 	 * we need to resolve a TS label.
18525 	 */
18526 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18527 	    !IPCL_IS_CONNECTED(connp) ||
18528 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18529 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18530 	    !connp->conn_ulp_labeled ||
18531 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18532 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18533 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18534 		if (tcp->tcp_snd_zcopy_aware)
18535 			mp = tcp_zcopy_disable(tcp, mp);
18536 		TCP_STAT(tcps, tcp_ip_send);
18537 		CALL_IP_WPUT(connp, q, mp);
18538 		return;
18539 	}
18540 
18541 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18542 		if (tcp->tcp_snd_zcopy_aware)
18543 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18544 		CALL_IP_WPUT(connp, q, mp);
18545 		return;
18546 	}
18547 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18548 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18549 
18550 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18551 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18552 #ifndef _BIG_ENDIAN
18553 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18554 #endif
18555 
18556 	/*
18557 	 * Check to see if we need to re-enable LSO/MDT for this connection
18558 	 * because it was previously disabled due to changes in the ill;
18559 	 * note that by doing it here, this re-enabling only applies when
18560 	 * the packet is not dispatched through CALL_IP_WPUT().
18561 	 *
18562 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18563 	 * case, since that's how we ended up here.  For IPv6, we do the
18564 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18565 	 */
18566 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18567 		/*
18568 		 * Restore LSO for this connection, so that next time around
18569 		 * it is eligible to go through tcp_lsosend() path again.
18570 		 */
18571 		TCP_STAT(tcps, tcp_lso_enabled);
18572 		tcp->tcp_lso = B_TRUE;
18573 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18574 		    "interface %s\n", (void *)connp, ill->ill_name));
18575 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18576 		/*
18577 		 * Restore MDT for this connection, so that next time around
18578 		 * it is eligible to go through tcp_multisend() path again.
18579 		 */
18580 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18581 		tcp->tcp_mdt = B_TRUE;
18582 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18583 		    "interface %s\n", (void *)connp, ill->ill_name));
18584 	}
18585 
18586 	if (tcp->tcp_snd_zcopy_aware) {
18587 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18588 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18589 			mp = tcp_zcopy_disable(tcp, mp);
18590 		/*
18591 		 * we shouldn't need to reset ipha as the mp containing
18592 		 * ipha should never be a zero-copy mp.
18593 		 */
18594 	}
18595 
18596 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18597 		ASSERT(ill->ill_hcksum_capab != NULL);
18598 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18599 	}
18600 
18601 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18602 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18603 
18604 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18605 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18606 
18607 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18608 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18609 
18610 	/* Software checksum? */
18611 	if (DB_CKSUMFLAGS(mp) == 0) {
18612 		TCP_STAT(tcps, tcp_out_sw_cksum);
18613 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18614 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18615 	}
18616 
18617 	/* Calculate IP header checksum if hardware isn't capable */
18618 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18619 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18620 		    ((uint16_t *)ipha)[4]);
18621 	}
18622 
18623 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18624 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18625 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18626 
18627 	UPDATE_OB_PKT_COUNT(ire);
18628 	ire->ire_last_used_time = lbolt;
18629 
18630 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18631 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18632 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18633 	    ntohs(ipha->ipha_length));
18634 
18635 	DTRACE_PROBE4(ip4__physical__out__start,
18636 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
18637 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
18638 	    ipst->ips_ipv4firewall_physical_out,
18639 	    NULL, ill, ipha, mp, mp, 0, ipst);
18640 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
18641 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
18642 
18643 	if (mp != NULL) {
18644 		if (ipst->ips_ip4_observe.he_interested) {
18645 			zoneid_t szone;
18646 
18647 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
18648 			    ipst, ALL_ZONES);
18649 
18650 			/*
18651 			 * The IP observability hook expects b_rptr to be
18652 			 * where the IP header starts, so advance past the
18653 			 * link layer header.
18654 			 */
18655 			mp->b_rptr += ire_fp_mp_len;
18656 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
18657 			    ALL_ZONES, ill, ipst);
18658 			mp->b_rptr -= ire_fp_mp_len;
18659 		}
18660 
18661 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
18662 	}
18663 
18664 	IRE_REFRELE(ire);
18665 }
18666 
18667 /*
18668  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18669  * if the receiver shrinks the window, i.e. moves the right window to the
18670  * left, the we should not send new data, but should retransmit normally the
18671  * old unacked data between suna and suna + swnd. We might has sent data
18672  * that is now outside the new window, pretend that we didn't send  it.
18673  */
18674 static void
18675 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18676 {
18677 	uint32_t	snxt = tcp->tcp_snxt;
18678 
18679 	ASSERT(shrunk_count > 0);
18680 
18681 	if (!tcp->tcp_is_wnd_shrnk) {
18682 		tcp->tcp_snxt_shrunk = snxt;
18683 		tcp->tcp_is_wnd_shrnk = B_TRUE;
18684 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
18685 		tcp->tcp_snxt_shrunk = snxt;
18686 	}
18687 
18688 	/* Pretend we didn't send the data outside the window */
18689 	snxt -= shrunk_count;
18690 
18691 	/* Reset all the values per the now shrunk window */
18692 	tcp_update_xmit_tail(tcp, snxt);
18693 	tcp->tcp_unsent += shrunk_count;
18694 
18695 	/*
18696 	 * If the SACK option is set, delete the entire list of
18697 	 * notsack'ed blocks.
18698 	 */
18699 	if (tcp->tcp_sack_info != NULL) {
18700 		if (tcp->tcp_notsack_list != NULL)
18701 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
18702 	}
18703 
18704 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18705 		/*
18706 		 * Make sure the timer is running so that we will probe a zero
18707 		 * window.
18708 		 */
18709 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18710 }
18711 
18712 
18713 /*
18714  * The TCP normal data output path.
18715  * NOTE: the logic of the fast path is duplicated from this function.
18716  */
18717 static void
18718 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18719 {
18720 	int		len;
18721 	mblk_t		*local_time;
18722 	mblk_t		*mp1;
18723 	uint32_t	snxt;
18724 	int		tail_unsent;
18725 	int		tcpstate;
18726 	int		usable = 0;
18727 	mblk_t		*xmit_tail;
18728 	queue_t		*q = tcp->tcp_wq;
18729 	int32_t		mss;
18730 	int32_t		num_sack_blk = 0;
18731 	int32_t		tcp_hdr_len;
18732 	int32_t		tcp_tcp_hdr_len;
18733 	int		mdt_thres;
18734 	int		rc;
18735 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18736 	ip_stack_t	*ipst;
18737 
18738 	tcpstate = tcp->tcp_state;
18739 	if (mp == NULL) {
18740 		/*
18741 		 * tcp_wput_data() with NULL mp should only be called when
18742 		 * there is unsent data.
18743 		 */
18744 		ASSERT(tcp->tcp_unsent > 0);
18745 		/* Really tacky... but we need this for detached closes. */
18746 		len = tcp->tcp_unsent;
18747 		goto data_null;
18748 	}
18749 
18750 #if CCS_STATS
18751 	wrw_stats.tot.count++;
18752 	wrw_stats.tot.bytes += msgdsize(mp);
18753 #endif
18754 	ASSERT(mp->b_datap->db_type == M_DATA);
18755 	/*
18756 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18757 	 * or before a connection attempt has begun.
18758 	 */
18759 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18760 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18761 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18762 #ifdef DEBUG
18763 			cmn_err(CE_WARN,
18764 			    "tcp_wput_data: data after ordrel, %s",
18765 			    tcp_display(tcp, NULL,
18766 			    DISP_ADDR_AND_PORT));
18767 #else
18768 			if (tcp->tcp_debug) {
18769 				(void) strlog(TCP_MOD_ID, 0, 1,
18770 				    SL_TRACE|SL_ERROR,
18771 				    "tcp_wput_data: data after ordrel, %s\n",
18772 				    tcp_display(tcp, NULL,
18773 				    DISP_ADDR_AND_PORT));
18774 			}
18775 #endif /* DEBUG */
18776 		}
18777 		if (tcp->tcp_snd_zcopy_aware &&
18778 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18779 			tcp_zcopy_notify(tcp);
18780 		freemsg(mp);
18781 		mutex_enter(&tcp->tcp_non_sq_lock);
18782 		if (tcp->tcp_flow_stopped &&
18783 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18784 			tcp_clrqfull(tcp);
18785 		}
18786 		mutex_exit(&tcp->tcp_non_sq_lock);
18787 		return;
18788 	}
18789 
18790 	/* Strip empties */
18791 	for (;;) {
18792 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18793 		    (uintptr_t)INT_MAX);
18794 		len = (int)(mp->b_wptr - mp->b_rptr);
18795 		if (len > 0)
18796 			break;
18797 		mp1 = mp;
18798 		mp = mp->b_cont;
18799 		freeb(mp1);
18800 		if (!mp) {
18801 			return;
18802 		}
18803 	}
18804 
18805 	/* If we are the first on the list ... */
18806 	if (tcp->tcp_xmit_head == NULL) {
18807 		tcp->tcp_xmit_head = mp;
18808 		tcp->tcp_xmit_tail = mp;
18809 		tcp->tcp_xmit_tail_unsent = len;
18810 	} else {
18811 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18812 		struct datab *dp;
18813 
18814 		mp1 = tcp->tcp_xmit_last;
18815 		if (len < tcp_tx_pull_len &&
18816 		    (dp = mp1->b_datap)->db_ref == 1 &&
18817 		    dp->db_lim - mp1->b_wptr >= len) {
18818 			ASSERT(len > 0);
18819 			ASSERT(!mp1->b_cont);
18820 			if (len == 1) {
18821 				*mp1->b_wptr++ = *mp->b_rptr;
18822 			} else {
18823 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18824 				mp1->b_wptr += len;
18825 			}
18826 			if (mp1 == tcp->tcp_xmit_tail)
18827 				tcp->tcp_xmit_tail_unsent += len;
18828 			mp1->b_cont = mp->b_cont;
18829 			if (tcp->tcp_snd_zcopy_aware &&
18830 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18831 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18832 			freeb(mp);
18833 			mp = mp1;
18834 		} else {
18835 			tcp->tcp_xmit_last->b_cont = mp;
18836 		}
18837 		len += tcp->tcp_unsent;
18838 	}
18839 
18840 	/* Tack on however many more positive length mblks we have */
18841 	if ((mp1 = mp->b_cont) != NULL) {
18842 		do {
18843 			int tlen;
18844 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18845 			    (uintptr_t)INT_MAX);
18846 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18847 			if (tlen <= 0) {
18848 				mp->b_cont = mp1->b_cont;
18849 				freeb(mp1);
18850 			} else {
18851 				len += tlen;
18852 				mp = mp1;
18853 			}
18854 		} while ((mp1 = mp->b_cont) != NULL);
18855 	}
18856 	tcp->tcp_xmit_last = mp;
18857 	tcp->tcp_unsent = len;
18858 
18859 	if (urgent)
18860 		usable = 1;
18861 
18862 data_null:
18863 	snxt = tcp->tcp_snxt;
18864 	xmit_tail = tcp->tcp_xmit_tail;
18865 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18866 
18867 	/*
18868 	 * Note that tcp_mss has been adjusted to take into account the
18869 	 * timestamp option if applicable.  Because SACK options do not
18870 	 * appear in every TCP segments and they are of variable lengths,
18871 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18872 	 * the actual segment length when we need to send a segment which
18873 	 * includes SACK options.
18874 	 */
18875 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18876 		int32_t	opt_len;
18877 
18878 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18879 		    tcp->tcp_num_sack_blk);
18880 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18881 		    2 + TCPOPT_HEADER_LEN;
18882 		mss = tcp->tcp_mss - opt_len;
18883 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18884 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18885 	} else {
18886 		mss = tcp->tcp_mss;
18887 		tcp_hdr_len = tcp->tcp_hdr_len;
18888 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18889 	}
18890 
18891 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18892 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18893 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18894 	}
18895 	if (tcpstate == TCPS_SYN_RCVD) {
18896 		/*
18897 		 * The three-way connection establishment handshake is not
18898 		 * complete yet. We want to queue the data for transmission
18899 		 * after entering ESTABLISHED state (RFC793). A jump to
18900 		 * "done" label effectively leaves data on the queue.
18901 		 */
18902 		goto done;
18903 	} else {
18904 		int usable_r;
18905 
18906 		/*
18907 		 * In the special case when cwnd is zero, which can only
18908 		 * happen if the connection is ECN capable, return now.
18909 		 * New segments is sent using tcp_timer().  The timer
18910 		 * is set in tcp_rput_data().
18911 		 */
18912 		if (tcp->tcp_cwnd == 0) {
18913 			/*
18914 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18915 			 * finished.
18916 			 */
18917 			ASSERT(tcp->tcp_ecn_ok ||
18918 			    tcp->tcp_state < TCPS_ESTABLISHED);
18919 			return;
18920 		}
18921 
18922 		/* NOTE: trouble if xmitting while SYN not acked? */
18923 		usable_r = snxt - tcp->tcp_suna;
18924 		usable_r = tcp->tcp_swnd - usable_r;
18925 
18926 		/*
18927 		 * Check if the receiver has shrunk the window.  If
18928 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18929 		 * cannot be set as there is unsent data, so FIN cannot
18930 		 * be sent out.  Otherwise, we need to take into account
18931 		 * of FIN as it consumes an "invisible" sequence number.
18932 		 */
18933 		ASSERT(tcp->tcp_fin_sent == 0);
18934 		if (usable_r < 0) {
18935 			/*
18936 			 * The receiver has shrunk the window and we have sent
18937 			 * -usable_r date beyond the window, re-adjust.
18938 			 *
18939 			 * If TCP window scaling is enabled, there can be
18940 			 * round down error as the advertised receive window
18941 			 * is actually right shifted n bits.  This means that
18942 			 * the lower n bits info is wiped out.  It will look
18943 			 * like the window is shrunk.  Do a check here to
18944 			 * see if the shrunk amount is actually within the
18945 			 * error in window calculation.  If it is, just
18946 			 * return.  Note that this check is inside the
18947 			 * shrunk window check.  This makes sure that even
18948 			 * though tcp_process_shrunk_swnd() is not called,
18949 			 * we will stop further processing.
18950 			 */
18951 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18952 				tcp_process_shrunk_swnd(tcp, -usable_r);
18953 			}
18954 			return;
18955 		}
18956 
18957 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18958 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18959 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18960 
18961 		/* usable = MIN(usable, unsent) */
18962 		if (usable_r > len)
18963 			usable_r = len;
18964 
18965 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18966 		if (usable_r > 0) {
18967 			usable = usable_r;
18968 		} else {
18969 			/* Bypass all other unnecessary processing. */
18970 			goto done;
18971 		}
18972 	}
18973 
18974 	local_time = (mblk_t *)lbolt;
18975 
18976 	/*
18977 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18978 	 * BSD.  This is more in line with the true intent of Nagle.
18979 	 *
18980 	 * The conditions are:
18981 	 * 1. The amount of unsent data (or amount of data which can be
18982 	 *    sent, whichever is smaller) is less than Nagle limit.
18983 	 * 2. The last sent size is also less than Nagle limit.
18984 	 * 3. There is unack'ed data.
18985 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18986 	 *    Nagle algorithm.  This reduces the probability that urgent
18987 	 *    bytes get "merged" together.
18988 	 * 5. The app has not closed the connection.  This eliminates the
18989 	 *    wait time of the receiving side waiting for the last piece of
18990 	 *    (small) data.
18991 	 *
18992 	 * If all are satisified, exit without sending anything.  Note
18993 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18994 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18995 	 * 4095).
18996 	 */
18997 	if (usable < (int)tcp->tcp_naglim &&
18998 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18999 	    snxt != tcp->tcp_suna &&
19000 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19001 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19002 		goto done;
19003 	}
19004 
19005 	/*
19006 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
19007 	 * is set, then we have to force TCP not to send partial segment
19008 	 * (smaller than MSS bytes). We are calculating the usable now
19009 	 * based on full mss and will save the rest of remaining data for
19010 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
19011 	 * something to do zero window probe.
19012 	 */
19013 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
19014 		if (usable < mss)
19015 			goto done;
19016 		usable = (usable / mss) * mss;
19017 	}
19018 
19019 	/* Update the latest receive window size in TCP header. */
19020 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19021 	    tcp->tcp_tcph->th_win);
19022 
19023 	/*
19024 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19025 	 *
19026 	 * 1. Simple TCP/IP{v4,v6} (no options).
19027 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19028 	 * 3. If the TCP connection is in ESTABLISHED state.
19029 	 * 4. The TCP is not detached.
19030 	 *
19031 	 * If any of the above conditions have changed during the
19032 	 * connection, stop using LSO/MDT and restore the stream head
19033 	 * parameters accordingly.
19034 	 */
19035 	ipst = tcps->tcps_netstack->netstack_ip;
19036 
19037 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19038 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19039 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19040 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19041 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19042 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19043 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19044 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19045 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19046 		if (tcp->tcp_lso) {
19047 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19048 			tcp->tcp_lso = B_FALSE;
19049 		} else {
19050 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19051 			tcp->tcp_mdt = B_FALSE;
19052 		}
19053 
19054 		/* Anything other than detached is considered pathological */
19055 		if (!TCP_IS_DETACHED(tcp)) {
19056 			if (tcp->tcp_lso)
19057 				TCP_STAT(tcps, tcp_lso_disabled);
19058 			else
19059 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19060 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19061 		}
19062 	}
19063 
19064 	/* Use MDT if sendable amount is greater than the threshold */
19065 	if (tcp->tcp_mdt &&
19066 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19067 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19068 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19069 	    (tcp->tcp_valid_bits == 0 ||
19070 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19071 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19072 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19073 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19074 		    local_time, mdt_thres);
19075 	} else {
19076 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19077 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19078 		    local_time, INT_MAX);
19079 	}
19080 
19081 	/* Pretend that all we were trying to send really got sent */
19082 	if (rc < 0 && tail_unsent < 0) {
19083 		do {
19084 			xmit_tail = xmit_tail->b_cont;
19085 			xmit_tail->b_prev = local_time;
19086 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19087 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19088 			tail_unsent += (int)(xmit_tail->b_wptr -
19089 			    xmit_tail->b_rptr);
19090 		} while (tail_unsent < 0);
19091 	}
19092 done:;
19093 	tcp->tcp_xmit_tail = xmit_tail;
19094 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19095 	len = tcp->tcp_snxt - snxt;
19096 	if (len) {
19097 		/*
19098 		 * If new data was sent, need to update the notsack
19099 		 * list, which is, afterall, data blocks that have
19100 		 * not been sack'ed by the receiver.  New data is
19101 		 * not sack'ed.
19102 		 */
19103 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19104 			/* len is a negative value. */
19105 			tcp->tcp_pipe -= len;
19106 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19107 			    tcp->tcp_snxt, snxt,
19108 			    &(tcp->tcp_num_notsack_blk),
19109 			    &(tcp->tcp_cnt_notsack_list));
19110 		}
19111 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19112 		tcp->tcp_rack = tcp->tcp_rnxt;
19113 		tcp->tcp_rack_cnt = 0;
19114 		if ((snxt + len) == tcp->tcp_suna) {
19115 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19116 		}
19117 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19118 		/*
19119 		 * Didn't send anything. Make sure the timer is running
19120 		 * so that we will probe a zero window.
19121 		 */
19122 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19123 	}
19124 	/* Note that len is the amount we just sent but with a negative sign */
19125 	tcp->tcp_unsent += len;
19126 	mutex_enter(&tcp->tcp_non_sq_lock);
19127 	if (tcp->tcp_flow_stopped) {
19128 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19129 			tcp_clrqfull(tcp);
19130 		}
19131 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19132 		tcp_setqfull(tcp);
19133 	}
19134 	mutex_exit(&tcp->tcp_non_sq_lock);
19135 }
19136 
19137 /*
19138  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19139  * outgoing TCP header with the template header, as well as other
19140  * options such as time-stamp, ECN and/or SACK.
19141  */
19142 static void
19143 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19144 {
19145 	tcph_t *tcp_tmpl, *tcp_h;
19146 	uint32_t *dst, *src;
19147 	int hdrlen;
19148 
19149 	ASSERT(OK_32PTR(rptr));
19150 
19151 	/* Template header */
19152 	tcp_tmpl = tcp->tcp_tcph;
19153 
19154 	/* Header of outgoing packet */
19155 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19156 
19157 	/* dst and src are opaque 32-bit fields, used for copying */
19158 	dst = (uint32_t *)rptr;
19159 	src = (uint32_t *)tcp->tcp_iphc;
19160 	hdrlen = tcp->tcp_hdr_len;
19161 
19162 	/* Fill time-stamp option if needed */
19163 	if (tcp->tcp_snd_ts_ok) {
19164 		U32_TO_BE32((uint32_t)now,
19165 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19166 		U32_TO_BE32(tcp->tcp_ts_recent,
19167 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19168 	} else {
19169 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19170 	}
19171 
19172 	/*
19173 	 * Copy the template header; is this really more efficient than
19174 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19175 	 * but perhaps not for other scenarios.
19176 	 */
19177 	dst[0] = src[0];
19178 	dst[1] = src[1];
19179 	dst[2] = src[2];
19180 	dst[3] = src[3];
19181 	dst[4] = src[4];
19182 	dst[5] = src[5];
19183 	dst[6] = src[6];
19184 	dst[7] = src[7];
19185 	dst[8] = src[8];
19186 	dst[9] = src[9];
19187 	if (hdrlen -= 40) {
19188 		hdrlen >>= 2;
19189 		dst += 10;
19190 		src += 10;
19191 		do {
19192 			*dst++ = *src++;
19193 		} while (--hdrlen);
19194 	}
19195 
19196 	/*
19197 	 * Set the ECN info in the TCP header if it is not a zero
19198 	 * window probe.  Zero window probe is only sent in
19199 	 * tcp_wput_data() and tcp_timer().
19200 	 */
19201 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19202 		SET_ECT(tcp, rptr);
19203 
19204 		if (tcp->tcp_ecn_echo_on)
19205 			tcp_h->th_flags[0] |= TH_ECE;
19206 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19207 			tcp_h->th_flags[0] |= TH_CWR;
19208 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19209 		}
19210 	}
19211 
19212 	/* Fill in SACK options */
19213 	if (num_sack_blk > 0) {
19214 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19215 		sack_blk_t *tmp;
19216 		int32_t	i;
19217 
19218 		wptr[0] = TCPOPT_NOP;
19219 		wptr[1] = TCPOPT_NOP;
19220 		wptr[2] = TCPOPT_SACK;
19221 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19222 		    sizeof (sack_blk_t);
19223 		wptr += TCPOPT_REAL_SACK_LEN;
19224 
19225 		tmp = tcp->tcp_sack_list;
19226 		for (i = 0; i < num_sack_blk; i++) {
19227 			U32_TO_BE32(tmp[i].begin, wptr);
19228 			wptr += sizeof (tcp_seq);
19229 			U32_TO_BE32(tmp[i].end, wptr);
19230 			wptr += sizeof (tcp_seq);
19231 		}
19232 		tcp_h->th_offset_and_rsrvd[0] +=
19233 		    ((num_sack_blk * 2 + 1) << 4);
19234 	}
19235 }
19236 
19237 /*
19238  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19239  * the destination address and SAP attribute, and if necessary, the
19240  * hardware checksum offload attribute to a Multidata message.
19241  */
19242 static int
19243 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19244     const uint32_t start, const uint32_t stuff, const uint32_t end,
19245     const uint32_t flags, tcp_stack_t *tcps)
19246 {
19247 	/* Add global destination address & SAP attribute */
19248 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19249 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19250 		    "destination address+SAP\n"));
19251 
19252 		if (dlmp != NULL)
19253 			TCP_STAT(tcps, tcp_mdt_allocfail);
19254 		return (-1);
19255 	}
19256 
19257 	/* Add global hwcksum attribute */
19258 	if (hwcksum &&
19259 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19260 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19261 		    "checksum attribute\n"));
19262 
19263 		TCP_STAT(tcps, tcp_mdt_allocfail);
19264 		return (-1);
19265 	}
19266 
19267 	return (0);
19268 }
19269 
19270 /*
19271  * Smaller and private version of pdescinfo_t used specifically for TCP,
19272  * which allows for only two payload spans per packet.
19273  */
19274 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19275 
19276 /*
19277  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19278  * scheme, and returns one the following:
19279  *
19280  * -1 = failed allocation.
19281  *  0 = success; burst count reached, or usable send window is too small,
19282  *      and that we'd rather wait until later before sending again.
19283  */
19284 static int
19285 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19286     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19287     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19288     const int mdt_thres)
19289 {
19290 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19291 	multidata_t	*mmd;
19292 	uint_t		obsegs, obbytes, hdr_frag_sz;
19293 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19294 	int		num_burst_seg, max_pld;
19295 	pdesc_t		*pkt;
19296 	tcp_pdescinfo_t	tcp_pkt_info;
19297 	pdescinfo_t	*pkt_info;
19298 	int		pbuf_idx, pbuf_idx_nxt;
19299 	int		seg_len, len, spill, af;
19300 	boolean_t	add_buffer, zcopy, clusterwide;
19301 	boolean_t	rconfirm = B_FALSE;
19302 	boolean_t	done = B_FALSE;
19303 	uint32_t	cksum;
19304 	uint32_t	hwcksum_flags;
19305 	ire_t		*ire = NULL;
19306 	ill_t		*ill;
19307 	ipha_t		*ipha;
19308 	ip6_t		*ip6h;
19309 	ipaddr_t	src, dst;
19310 	ill_zerocopy_capab_t *zc_cap = NULL;
19311 	uint16_t	*up;
19312 	int		err;
19313 	conn_t		*connp;
19314 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19315 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19316 	int		usable_mmd, tail_unsent_mmd;
19317 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
19318 	mblk_t		*xmit_tail_mmd;
19319 	netstackid_t	stack_id;
19320 
19321 #ifdef	_BIG_ENDIAN
19322 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19323 #else
19324 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19325 #endif
19326 
19327 #define	PREP_NEW_MULTIDATA() {			\
19328 	mmd = NULL;				\
19329 	md_mp = md_hbuf = NULL;			\
19330 	cur_hdr_off = 0;			\
19331 	max_pld = tcp->tcp_mdt_max_pld;		\
19332 	pbuf_idx = pbuf_idx_nxt = -1;		\
19333 	add_buffer = B_TRUE;			\
19334 	zcopy = B_FALSE;			\
19335 }
19336 
19337 #define	PREP_NEW_PBUF() {			\
19338 	md_pbuf = md_pbuf_nxt = NULL;		\
19339 	pbuf_idx = pbuf_idx_nxt = -1;		\
19340 	cur_pld_off = 0;			\
19341 	first_snxt = *snxt;			\
19342 	ASSERT(*tail_unsent > 0);		\
19343 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19344 }
19345 
19346 	ASSERT(mdt_thres >= mss);
19347 	ASSERT(*usable > 0 && *usable > mdt_thres);
19348 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19349 	ASSERT(!TCP_IS_DETACHED(tcp));
19350 	ASSERT(tcp->tcp_valid_bits == 0 ||
19351 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19352 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19353 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19354 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19355 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19356 
19357 	connp = tcp->tcp_connp;
19358 	ASSERT(connp != NULL);
19359 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19360 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19361 
19362 	stack_id = connp->conn_netstack->netstack_stackid;
19363 
19364 	usable_mmd = tail_unsent_mmd = 0;
19365 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
19366 	xmit_tail_mmd = NULL;
19367 	/*
19368 	 * Note that tcp will only declare at most 2 payload spans per
19369 	 * packet, which is much lower than the maximum allowable number
19370 	 * of packet spans per Multidata.  For this reason, we use the
19371 	 * privately declared and smaller descriptor info structure, in
19372 	 * order to save some stack space.
19373 	 */
19374 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19375 
19376 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19377 	if (af == AF_INET) {
19378 		dst = tcp->tcp_ipha->ipha_dst;
19379 		src = tcp->tcp_ipha->ipha_src;
19380 		ASSERT(!CLASSD(dst));
19381 	}
19382 	ASSERT(af == AF_INET ||
19383 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19384 
19385 	obsegs = obbytes = 0;
19386 	num_burst_seg = tcp->tcp_snd_burst;
19387 	md_mp_head = NULL;
19388 	PREP_NEW_MULTIDATA();
19389 
19390 	/*
19391 	 * Before we go on further, make sure there is an IRE that we can
19392 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19393 	 * in proceeding any further, and we should just hand everything
19394 	 * off to the legacy path.
19395 	 */
19396 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19397 		goto legacy_send_no_md;
19398 
19399 	ASSERT(ire != NULL);
19400 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19401 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19402 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19403 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19404 	/*
19405 	 * If we do support loopback for MDT (which requires modifications
19406 	 * to the receiving paths), the following assertions should go away,
19407 	 * and we would be sending the Multidata to loopback conn later on.
19408 	 */
19409 	ASSERT(!IRE_IS_LOCAL(ire));
19410 	ASSERT(ire->ire_stq != NULL);
19411 
19412 	ill = ire_to_ill(ire);
19413 	ASSERT(ill != NULL);
19414 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19415 
19416 	if (!tcp->tcp_ire_ill_check_done) {
19417 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19418 		tcp->tcp_ire_ill_check_done = B_TRUE;
19419 	}
19420 
19421 	/*
19422 	 * If the underlying interface conditions have changed, or if the
19423 	 * new interface does not support MDT, go back to legacy path.
19424 	 */
19425 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19426 		/* don't go through this path anymore for this connection */
19427 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19428 		tcp->tcp_mdt = B_FALSE;
19429 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19430 		    "interface %s\n", (void *)connp, ill->ill_name));
19431 		/* IRE will be released prior to returning */
19432 		goto legacy_send_no_md;
19433 	}
19434 
19435 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19436 		zc_cap = ill->ill_zerocopy_capab;
19437 
19438 	/*
19439 	 * Check if we can take tcp fast-path. Note that "incomplete"
19440 	 * ire's (where the link-layer for next hop is not resolved
19441 	 * or where the fast-path header in nce_fp_mp is not available
19442 	 * yet) are sent down the legacy (slow) path.
19443 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19444 	 */
19445 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19446 		/* IRE will be released prior to returning */
19447 		goto legacy_send_no_md;
19448 	}
19449 
19450 	/* go to legacy path if interface doesn't support zerocopy */
19451 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19452 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19453 		/* IRE will be released prior to returning */
19454 		goto legacy_send_no_md;
19455 	}
19456 
19457 	/* does the interface support hardware checksum offload? */
19458 	hwcksum_flags = 0;
19459 	if (ILL_HCKSUM_CAPABLE(ill) &&
19460 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19461 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19462 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19463 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19464 		    HCKSUM_IPHDRCKSUM)
19465 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19466 
19467 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19468 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19469 			hwcksum_flags |= HCK_FULLCKSUM;
19470 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19471 		    HCKSUM_INET_PARTIAL)
19472 			hwcksum_flags |= HCK_PARTIALCKSUM;
19473 	}
19474 
19475 	/*
19476 	 * Each header fragment consists of the leading extra space,
19477 	 * followed by the TCP/IP header, and the trailing extra space.
19478 	 * We make sure that each header fragment begins on a 32-bit
19479 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19480 	 * aligned in tcp_mdt_update).
19481 	 */
19482 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19483 	    tcp->tcp_mdt_hdr_tail), 4);
19484 
19485 	/* are we starting from the beginning of data block? */
19486 	if (*tail_unsent == 0) {
19487 		*xmit_tail = (*xmit_tail)->b_cont;
19488 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19489 		*tail_unsent = (int)MBLKL(*xmit_tail);
19490 	}
19491 
19492 	/*
19493 	 * Here we create one or more Multidata messages, each made up of
19494 	 * one header buffer and up to N payload buffers.  This entire
19495 	 * operation is done within two loops:
19496 	 *
19497 	 * The outer loop mostly deals with creating the Multidata message,
19498 	 * as well as the header buffer that gets added to it.  It also
19499 	 * links the Multidata messages together such that all of them can
19500 	 * be sent down to the lower layer in a single putnext call; this
19501 	 * linking behavior depends on the tcp_mdt_chain tunable.
19502 	 *
19503 	 * The inner loop takes an existing Multidata message, and adds
19504 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19505 	 * packetizes those buffers by filling up the corresponding header
19506 	 * buffer fragments with the proper IP and TCP headers, and by
19507 	 * describing the layout of each packet in the packet descriptors
19508 	 * that get added to the Multidata.
19509 	 */
19510 	do {
19511 		/*
19512 		 * If usable send window is too small, or data blocks in
19513 		 * transmit list are smaller than our threshold (i.e. app
19514 		 * performs large writes followed by small ones), we hand
19515 		 * off the control over to the legacy path.  Note that we'll
19516 		 * get back the control once it encounters a large block.
19517 		 */
19518 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19519 		    (*xmit_tail)->b_cont != NULL &&
19520 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19521 			/* send down what we've got so far */
19522 			if (md_mp_head != NULL) {
19523 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19524 				    obsegs, obbytes, &rconfirm);
19525 			}
19526 			/*
19527 			 * Pass control over to tcp_send(), but tell it to
19528 			 * return to us once a large-size transmission is
19529 			 * possible.
19530 			 */
19531 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19532 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19533 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19534 			    tail_unsent, xmit_tail, local_time,
19535 			    mdt_thres)) <= 0) {
19536 				/* burst count reached, or alloc failed */
19537 				IRE_REFRELE(ire);
19538 				return (err);
19539 			}
19540 
19541 			/* tcp_send() may have sent everything, so check */
19542 			if (*usable <= 0) {
19543 				IRE_REFRELE(ire);
19544 				return (0);
19545 			}
19546 
19547 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19548 			/*
19549 			 * We may have delivered the Multidata, so make sure
19550 			 * to re-initialize before the next round.
19551 			 */
19552 			md_mp_head = NULL;
19553 			obsegs = obbytes = 0;
19554 			num_burst_seg = tcp->tcp_snd_burst;
19555 			PREP_NEW_MULTIDATA();
19556 
19557 			/* are we starting from the beginning of data block? */
19558 			if (*tail_unsent == 0) {
19559 				*xmit_tail = (*xmit_tail)->b_cont;
19560 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19561 				    (uintptr_t)INT_MAX);
19562 				*tail_unsent = (int)MBLKL(*xmit_tail);
19563 			}
19564 		}
19565 		/*
19566 		 * Record current values for parameters we may need to pass
19567 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
19568 		 * each iteration of the outer loop (each multidata message
19569 		 * creation). If we have a failure in the inner loop, we send
19570 		 * any complete multidata messages we have before reverting
19571 		 * to using the traditional non-md path.
19572 		 */
19573 		snxt_mmd = *snxt;
19574 		usable_mmd = *usable;
19575 		xmit_tail_mmd = *xmit_tail;
19576 		tail_unsent_mmd = *tail_unsent;
19577 		obsegs_mmd = obsegs;
19578 		obbytes_mmd = obbytes;
19579 
19580 		/*
19581 		 * max_pld limits the number of mblks in tcp's transmit
19582 		 * queue that can be added to a Multidata message.  Once
19583 		 * this counter reaches zero, no more additional mblks
19584 		 * can be added to it.  What happens afterwards depends
19585 		 * on whether or not we are set to chain the Multidata
19586 		 * messages.  If we are to link them together, reset
19587 		 * max_pld to its original value (tcp_mdt_max_pld) and
19588 		 * prepare to create a new Multidata message which will
19589 		 * get linked to md_mp_head.  Else, leave it alone and
19590 		 * let the inner loop break on its own.
19591 		 */
19592 		if (tcp_mdt_chain && max_pld == 0)
19593 			PREP_NEW_MULTIDATA();
19594 
19595 		/* adding a payload buffer; re-initialize values */
19596 		if (add_buffer)
19597 			PREP_NEW_PBUF();
19598 
19599 		/*
19600 		 * If we don't have a Multidata, either because we just
19601 		 * (re)entered this outer loop, or after we branched off
19602 		 * to tcp_send above, setup the Multidata and header
19603 		 * buffer to be used.
19604 		 */
19605 		if (md_mp == NULL) {
19606 			int md_hbuflen;
19607 			uint32_t start, stuff;
19608 
19609 			/*
19610 			 * Calculate Multidata header buffer size large enough
19611 			 * to hold all of the headers that can possibly be
19612 			 * sent at this moment.  We'd rather over-estimate
19613 			 * the size than running out of space; this is okay
19614 			 * since this buffer is small anyway.
19615 			 */
19616 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19617 
19618 			/*
19619 			 * Start and stuff offset for partial hardware
19620 			 * checksum offload; these are currently for IPv4.
19621 			 * For full checksum offload, they are set to zero.
19622 			 */
19623 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19624 				if (af == AF_INET) {
19625 					start = IP_SIMPLE_HDR_LENGTH;
19626 					stuff = IP_SIMPLE_HDR_LENGTH +
19627 					    TCP_CHECKSUM_OFFSET;
19628 				} else {
19629 					start = IPV6_HDR_LEN;
19630 					stuff = IPV6_HDR_LEN +
19631 					    TCP_CHECKSUM_OFFSET;
19632 				}
19633 			} else {
19634 				start = stuff = 0;
19635 			}
19636 
19637 			/*
19638 			 * Create the header buffer, Multidata, as well as
19639 			 * any necessary attributes (destination address,
19640 			 * SAP and hardware checksum offload) that should
19641 			 * be associated with the Multidata message.
19642 			 */
19643 			ASSERT(cur_hdr_off == 0);
19644 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19645 			    ((md_hbuf->b_wptr += md_hbuflen),
19646 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19647 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19648 			    /* fastpath mblk */
19649 			    ire->ire_nce->nce_res_mp,
19650 			    /* hardware checksum enabled */
19651 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19652 			    /* hardware checksum offsets */
19653 			    start, stuff, 0,
19654 			    /* hardware checksum flag */
19655 			    hwcksum_flags, tcps) != 0)) {
19656 legacy_send:
19657 				/*
19658 				 * We arrive here from a failure within the
19659 				 * inner (packetizer) loop or we fail one of
19660 				 * the conditionals above. We restore the
19661 				 * previously checkpointed values for:
19662 				 *    xmit_tail
19663 				 *    usable
19664 				 *    tail_unsent
19665 				 *    snxt
19666 				 *    obbytes
19667 				 *    obsegs
19668 				 * We should then be able to dispatch any
19669 				 * complete multidata before reverting to the
19670 				 * traditional path with consistent parameters
19671 				 * (the inner loop updates these as it
19672 				 * iterates).
19673 				 */
19674 				*xmit_tail = xmit_tail_mmd;
19675 				*usable = usable_mmd;
19676 				*tail_unsent = tail_unsent_mmd;
19677 				*snxt = snxt_mmd;
19678 				obbytes = obbytes_mmd;
19679 				obsegs = obsegs_mmd;
19680 				if (md_mp != NULL) {
19681 					/* Unlink message from the chain */
19682 					if (md_mp_head != NULL) {
19683 						err = (intptr_t)rmvb(md_mp_head,
19684 						    md_mp);
19685 						/*
19686 						 * We can't assert that rmvb
19687 						 * did not return -1, since we
19688 						 * may get here before linkb
19689 						 * happens.  We do, however,
19690 						 * check if we just removed the
19691 						 * only element in the list.
19692 						 */
19693 						if (err == 0)
19694 							md_mp_head = NULL;
19695 					}
19696 					/* md_hbuf gets freed automatically */
19697 					TCP_STAT(tcps, tcp_mdt_discarded);
19698 					freeb(md_mp);
19699 				} else {
19700 					/* Either allocb or mmd_alloc failed */
19701 					TCP_STAT(tcps, tcp_mdt_allocfail);
19702 					if (md_hbuf != NULL)
19703 						freeb(md_hbuf);
19704 				}
19705 
19706 				/* send down what we've got so far */
19707 				if (md_mp_head != NULL) {
19708 					tcp_multisend_data(tcp, ire, ill,
19709 					    md_mp_head, obsegs, obbytes,
19710 					    &rconfirm);
19711 				}
19712 legacy_send_no_md:
19713 				if (ire != NULL)
19714 					IRE_REFRELE(ire);
19715 				/*
19716 				 * Too bad; let the legacy path handle this.
19717 				 * We specify INT_MAX for the threshold, since
19718 				 * we gave up with the Multidata processings
19719 				 * and let the old path have it all.
19720 				 */
19721 				TCP_STAT(tcps, tcp_mdt_legacy_all);
19722 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19723 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19724 				    snxt, tail_unsent, xmit_tail, local_time,
19725 				    INT_MAX));
19726 			}
19727 
19728 			/* link to any existing ones, if applicable */
19729 			TCP_STAT(tcps, tcp_mdt_allocd);
19730 			if (md_mp_head == NULL) {
19731 				md_mp_head = md_mp;
19732 			} else if (tcp_mdt_chain) {
19733 				TCP_STAT(tcps, tcp_mdt_linked);
19734 				linkb(md_mp_head, md_mp);
19735 			}
19736 		}
19737 
19738 		ASSERT(md_mp_head != NULL);
19739 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19740 		ASSERT(md_mp != NULL && mmd != NULL);
19741 		ASSERT(md_hbuf != NULL);
19742 
19743 		/*
19744 		 * Packetize the transmittable portion of the data block;
19745 		 * each data block is essentially added to the Multidata
19746 		 * as a payload buffer.  We also deal with adding more
19747 		 * than one payload buffers, which happens when the remaining
19748 		 * packetized portion of the current payload buffer is less
19749 		 * than MSS, while the next data block in transmit queue
19750 		 * has enough data to make up for one.  This "spillover"
19751 		 * case essentially creates a split-packet, where portions
19752 		 * of the packet's payload fragments may span across two
19753 		 * virtually discontiguous address blocks.
19754 		 */
19755 		seg_len = mss;
19756 		do {
19757 			len = seg_len;
19758 
19759 			/* one must remain NULL for DTRACE_IP_FASTPATH */
19760 			ipha = NULL;
19761 			ip6h = NULL;
19762 
19763 			ASSERT(len > 0);
19764 			ASSERT(max_pld >= 0);
19765 			ASSERT(!add_buffer || cur_pld_off == 0);
19766 
19767 			/*
19768 			 * First time around for this payload buffer; note
19769 			 * in the case of a spillover, the following has
19770 			 * been done prior to adding the split-packet
19771 			 * descriptor to Multidata, and we don't want to
19772 			 * repeat the process.
19773 			 */
19774 			if (add_buffer) {
19775 				ASSERT(mmd != NULL);
19776 				ASSERT(md_pbuf == NULL);
19777 				ASSERT(md_pbuf_nxt == NULL);
19778 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19779 
19780 				/*
19781 				 * Have we reached the limit?  We'd get to
19782 				 * this case when we're not chaining the
19783 				 * Multidata messages together, and since
19784 				 * we're done, terminate this loop.
19785 				 */
19786 				if (max_pld == 0)
19787 					break; /* done */
19788 
19789 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19790 					TCP_STAT(tcps, tcp_mdt_allocfail);
19791 					goto legacy_send; /* out_of_mem */
19792 				}
19793 
19794 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19795 				    zc_cap != NULL) {
19796 					if (!ip_md_zcopy_attr(mmd, NULL,
19797 					    zc_cap->ill_zerocopy_flags)) {
19798 						freeb(md_pbuf);
19799 						TCP_STAT(tcps,
19800 						    tcp_mdt_allocfail);
19801 						/* out_of_mem */
19802 						goto legacy_send;
19803 					}
19804 					zcopy = B_TRUE;
19805 				}
19806 
19807 				md_pbuf->b_rptr += base_pld_off;
19808 
19809 				/*
19810 				 * Add a payload buffer to the Multidata; this
19811 				 * operation must not fail, or otherwise our
19812 				 * logic in this routine is broken.  There
19813 				 * is no memory allocation done by the
19814 				 * routine, so any returned failure simply
19815 				 * tells us that we've done something wrong.
19816 				 *
19817 				 * A failure tells us that either we're adding
19818 				 * the same payload buffer more than once, or
19819 				 * we're trying to add more buffers than
19820 				 * allowed (max_pld calculation is wrong).
19821 				 * None of the above cases should happen, and
19822 				 * we panic because either there's horrible
19823 				 * heap corruption, and/or programming mistake.
19824 				 */
19825 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19826 				if (pbuf_idx < 0) {
19827 					cmn_err(CE_PANIC, "tcp_multisend: "
19828 					    "payload buffer logic error "
19829 					    "detected for tcp %p mmd %p "
19830 					    "pbuf %p (%d)\n",
19831 					    (void *)tcp, (void *)mmd,
19832 					    (void *)md_pbuf, pbuf_idx);
19833 				}
19834 
19835 				ASSERT(max_pld > 0);
19836 				--max_pld;
19837 				add_buffer = B_FALSE;
19838 			}
19839 
19840 			ASSERT(md_mp_head != NULL);
19841 			ASSERT(md_pbuf != NULL);
19842 			ASSERT(md_pbuf_nxt == NULL);
19843 			ASSERT(pbuf_idx != -1);
19844 			ASSERT(pbuf_idx_nxt == -1);
19845 			ASSERT(*usable > 0);
19846 
19847 			/*
19848 			 * We spillover to the next payload buffer only
19849 			 * if all of the following is true:
19850 			 *
19851 			 *   1. There is not enough data on the current
19852 			 *	payload buffer to make up `len',
19853 			 *   2. We are allowed to send `len',
19854 			 *   3. The next payload buffer length is large
19855 			 *	enough to accomodate `spill'.
19856 			 */
19857 			if ((spill = len - *tail_unsent) > 0 &&
19858 			    *usable >= len &&
19859 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19860 			    max_pld > 0) {
19861 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19862 				if (md_pbuf_nxt == NULL) {
19863 					TCP_STAT(tcps, tcp_mdt_allocfail);
19864 					goto legacy_send; /* out_of_mem */
19865 				}
19866 
19867 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19868 				    zc_cap != NULL) {
19869 					if (!ip_md_zcopy_attr(mmd, NULL,
19870 					    zc_cap->ill_zerocopy_flags)) {
19871 						freeb(md_pbuf_nxt);
19872 						TCP_STAT(tcps,
19873 						    tcp_mdt_allocfail);
19874 						/* out_of_mem */
19875 						goto legacy_send;
19876 					}
19877 					zcopy = B_TRUE;
19878 				}
19879 
19880 				/*
19881 				 * See comments above on the first call to
19882 				 * mmd_addpldbuf for explanation on the panic.
19883 				 */
19884 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19885 				if (pbuf_idx_nxt < 0) {
19886 					panic("tcp_multisend: "
19887 					    "next payload buffer logic error "
19888 					    "detected for tcp %p mmd %p "
19889 					    "pbuf %p (%d)\n",
19890 					    (void *)tcp, (void *)mmd,
19891 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19892 				}
19893 
19894 				ASSERT(max_pld > 0);
19895 				--max_pld;
19896 			} else if (spill > 0) {
19897 				/*
19898 				 * If there's a spillover, but the following
19899 				 * xmit_tail couldn't give us enough octets
19900 				 * to reach "len", then stop the current
19901 				 * Multidata creation and let the legacy
19902 				 * tcp_send() path take over.  We don't want
19903 				 * to send the tiny segment as part of this
19904 				 * Multidata for performance reasons; instead,
19905 				 * we let the legacy path deal with grouping
19906 				 * it with the subsequent small mblks.
19907 				 */
19908 				if (*usable >= len &&
19909 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19910 					max_pld = 0;
19911 					break;	/* done */
19912 				}
19913 
19914 				/*
19915 				 * We can't spillover, and we are near
19916 				 * the end of the current payload buffer,
19917 				 * so send what's left.
19918 				 */
19919 				ASSERT(*tail_unsent > 0);
19920 				len = *tail_unsent;
19921 			}
19922 
19923 			/* tail_unsent is negated if there is a spillover */
19924 			*tail_unsent -= len;
19925 			*usable -= len;
19926 			ASSERT(*usable >= 0);
19927 
19928 			if (*usable < mss)
19929 				seg_len = *usable;
19930 			/*
19931 			 * Sender SWS avoidance; see comments in tcp_send();
19932 			 * everything else is the same, except that we only
19933 			 * do this here if there is no more data to be sent
19934 			 * following the current xmit_tail.  We don't check
19935 			 * for 1-byte urgent data because we shouldn't get
19936 			 * here if TCP_URG_VALID is set.
19937 			 */
19938 			if (*usable > 0 && *usable < mss &&
19939 			    ((md_pbuf_nxt == NULL &&
19940 			    (*xmit_tail)->b_cont == NULL) ||
19941 			    (md_pbuf_nxt != NULL &&
19942 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19943 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19944 			    (tcp->tcp_unsent -
19945 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19946 			    !tcp->tcp_zero_win_probe) {
19947 				if ((*snxt + len) == tcp->tcp_snxt &&
19948 				    (*snxt + len) == tcp->tcp_suna) {
19949 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19950 				}
19951 				done = B_TRUE;
19952 			}
19953 
19954 			/*
19955 			 * Prime pump for IP's checksumming on our behalf;
19956 			 * include the adjustment for a source route if any.
19957 			 * Do this only for software/partial hardware checksum
19958 			 * offload, as this field gets zeroed out later for
19959 			 * the full hardware checksum offload case.
19960 			 */
19961 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19962 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19963 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19964 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19965 			}
19966 
19967 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19968 			*snxt += len;
19969 
19970 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19971 			/*
19972 			 * We set the PUSH bit only if TCP has no more buffered
19973 			 * data to be transmitted (or if sender SWS avoidance
19974 			 * takes place), as opposed to setting it for every
19975 			 * last packet in the burst.
19976 			 */
19977 			if (done ||
19978 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19979 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19980 
19981 			/*
19982 			 * Set FIN bit if this is our last segment; snxt
19983 			 * already includes its length, and it will not
19984 			 * be adjusted after this point.
19985 			 */
19986 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19987 			    *snxt == tcp->tcp_fss) {
19988 				if (!tcp->tcp_fin_acked) {
19989 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19990 					BUMP_MIB(&tcps->tcps_mib,
19991 					    tcpOutControl);
19992 				}
19993 				if (!tcp->tcp_fin_sent) {
19994 					tcp->tcp_fin_sent = B_TRUE;
19995 					/*
19996 					 * tcp state must be ESTABLISHED
19997 					 * in order for us to get here in
19998 					 * the first place.
19999 					 */
20000 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20001 
20002 					/*
20003 					 * Upon returning from this routine,
20004 					 * tcp_wput_data() will set tcp_snxt
20005 					 * to be equal to snxt + tcp_fin_sent.
20006 					 * This is essentially the same as
20007 					 * setting it to tcp_fss + 1.
20008 					 */
20009 				}
20010 			}
20011 
20012 			tcp->tcp_last_sent_len = (ushort_t)len;
20013 
20014 			len += tcp_hdr_len;
20015 			if (tcp->tcp_ipversion == IPV4_VERSION)
20016 				tcp->tcp_ipha->ipha_length = htons(len);
20017 			else
20018 				tcp->tcp_ip6h->ip6_plen = htons(len -
20019 				    ((char *)&tcp->tcp_ip6h[1] -
20020 				    tcp->tcp_iphc));
20021 
20022 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20023 
20024 			/* setup header fragment */
20025 			PDESC_HDR_ADD(pkt_info,
20026 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20027 			    tcp->tcp_mdt_hdr_head,		/* head room */
20028 			    tcp_hdr_len,			/* len */
20029 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20030 
20031 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20032 			    hdr_frag_sz);
20033 			ASSERT(MBLKIN(md_hbuf,
20034 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20035 			    PDESC_HDRSIZE(pkt_info)));
20036 
20037 			/* setup first payload fragment */
20038 			PDESC_PLD_INIT(pkt_info);
20039 			PDESC_PLD_SPAN_ADD(pkt_info,
20040 			    pbuf_idx,				/* index */
20041 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20042 			    tcp->tcp_last_sent_len);		/* len */
20043 
20044 			/* create a split-packet in case of a spillover */
20045 			if (md_pbuf_nxt != NULL) {
20046 				ASSERT(spill > 0);
20047 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20048 				ASSERT(!add_buffer);
20049 
20050 				md_pbuf = md_pbuf_nxt;
20051 				md_pbuf_nxt = NULL;
20052 				pbuf_idx = pbuf_idx_nxt;
20053 				pbuf_idx_nxt = -1;
20054 				cur_pld_off = spill;
20055 
20056 				/* trim out first payload fragment */
20057 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20058 
20059 				/* setup second payload fragment */
20060 				PDESC_PLD_SPAN_ADD(pkt_info,
20061 				    pbuf_idx,			/* index */
20062 				    md_pbuf->b_rptr,		/* start */
20063 				    spill);			/* len */
20064 
20065 				if ((*xmit_tail)->b_next == NULL) {
20066 					/*
20067 					 * Store the lbolt used for RTT
20068 					 * estimation. We can only record one
20069 					 * timestamp per mblk so we do it when
20070 					 * we reach the end of the payload
20071 					 * buffer.  Also we only take a new
20072 					 * timestamp sample when the previous
20073 					 * timed data from the same mblk has
20074 					 * been ack'ed.
20075 					 */
20076 					(*xmit_tail)->b_prev = local_time;
20077 					(*xmit_tail)->b_next =
20078 					    (mblk_t *)(uintptr_t)first_snxt;
20079 				}
20080 
20081 				first_snxt = *snxt - spill;
20082 
20083 				/*
20084 				 * Advance xmit_tail; usable could be 0 by
20085 				 * the time we got here, but we made sure
20086 				 * above that we would only spillover to
20087 				 * the next data block if usable includes
20088 				 * the spilled-over amount prior to the
20089 				 * subtraction.  Therefore, we are sure
20090 				 * that xmit_tail->b_cont can't be NULL.
20091 				 */
20092 				ASSERT((*xmit_tail)->b_cont != NULL);
20093 				*xmit_tail = (*xmit_tail)->b_cont;
20094 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20095 				    (uintptr_t)INT_MAX);
20096 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20097 			} else {
20098 				cur_pld_off += tcp->tcp_last_sent_len;
20099 			}
20100 
20101 			/*
20102 			 * Fill in the header using the template header, and
20103 			 * add options such as time-stamp, ECN and/or SACK,
20104 			 * as needed.
20105 			 */
20106 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20107 			    (clock_t)local_time, num_sack_blk);
20108 
20109 			/* take care of some IP header businesses */
20110 			if (af == AF_INET) {
20111 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20112 
20113 				ASSERT(OK_32PTR((uchar_t *)ipha));
20114 				ASSERT(PDESC_HDRL(pkt_info) >=
20115 				    IP_SIMPLE_HDR_LENGTH);
20116 				ASSERT(ipha->ipha_version_and_hdr_length ==
20117 				    IP_SIMPLE_HDR_VERSION);
20118 
20119 				/*
20120 				 * Assign ident value for current packet; see
20121 				 * related comments in ip_wput_ire() about the
20122 				 * contract private interface with clustering
20123 				 * group.
20124 				 */
20125 				clusterwide = B_FALSE;
20126 				if (cl_inet_ipident != NULL) {
20127 					ASSERT(cl_inet_isclusterwide != NULL);
20128 					if ((*cl_inet_isclusterwide)(stack_id,
20129 					    IPPROTO_IP, AF_INET,
20130 					    (uint8_t *)(uintptr_t)src, NULL)) {
20131 						ipha->ipha_ident =
20132 						    (*cl_inet_ipident)(stack_id,
20133 						    IPPROTO_IP, AF_INET,
20134 						    (uint8_t *)(uintptr_t)src,
20135 						    (uint8_t *)(uintptr_t)dst,
20136 						    NULL);
20137 						clusterwide = B_TRUE;
20138 					}
20139 				}
20140 
20141 				if (!clusterwide) {
20142 					ipha->ipha_ident = (uint16_t)
20143 					    atomic_add_32_nv(
20144 						&ire->ire_ident, 1);
20145 				}
20146 #ifndef _BIG_ENDIAN
20147 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20148 				    (ipha->ipha_ident >> 8);
20149 #endif
20150 			} else {
20151 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20152 
20153 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20154 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20155 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20156 				ASSERT(PDESC_HDRL(pkt_info) >=
20157 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20158 				    TCP_CHECKSUM_SIZE));
20159 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20160 
20161 				if (tcp->tcp_ip_forward_progress) {
20162 					rconfirm = B_TRUE;
20163 					tcp->tcp_ip_forward_progress = B_FALSE;
20164 				}
20165 			}
20166 
20167 			/* at least one payload span, and at most two */
20168 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20169 
20170 			/* add the packet descriptor to Multidata */
20171 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20172 			    KM_NOSLEEP)) == NULL) {
20173 				/*
20174 				 * Any failure other than ENOMEM indicates
20175 				 * that we have passed in invalid pkt_info
20176 				 * or parameters to mmd_addpdesc, which must
20177 				 * not happen.
20178 				 *
20179 				 * EINVAL is a result of failure on boundary
20180 				 * checks against the pkt_info contents.  It
20181 				 * should not happen, and we panic because
20182 				 * either there's horrible heap corruption,
20183 				 * and/or programming mistake.
20184 				 */
20185 				if (err != ENOMEM) {
20186 					cmn_err(CE_PANIC, "tcp_multisend: "
20187 					    "pdesc logic error detected for "
20188 					    "tcp %p mmd %p pinfo %p (%d)\n",
20189 					    (void *)tcp, (void *)mmd,
20190 					    (void *)pkt_info, err);
20191 				}
20192 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20193 				goto legacy_send; /* out_of_mem */
20194 			}
20195 			ASSERT(pkt != NULL);
20196 
20197 			/* calculate IP header and TCP checksums */
20198 			if (af == AF_INET) {
20199 				/* calculate pseudo-header checksum */
20200 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20201 				    (src >> 16) + (src & 0xFFFF);
20202 
20203 				/* offset for TCP header checksum */
20204 				up = IPH_TCPH_CHECKSUMP(ipha,
20205 				    IP_SIMPLE_HDR_LENGTH);
20206 			} else {
20207 				up = (uint16_t *)&ip6h->ip6_src;
20208 
20209 				/* calculate pseudo-header checksum */
20210 				cksum = up[0] + up[1] + up[2] + up[3] +
20211 				    up[4] + up[5] + up[6] + up[7] +
20212 				    up[8] + up[9] + up[10] + up[11] +
20213 				    up[12] + up[13] + up[14] + up[15];
20214 
20215 				/* Fold the initial sum */
20216 				cksum = (cksum & 0xffff) + (cksum >> 16);
20217 
20218 				up = (uint16_t *)(((uchar_t *)ip6h) +
20219 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20220 			}
20221 
20222 			if (hwcksum_flags & HCK_FULLCKSUM) {
20223 				/* clear checksum field for hardware */
20224 				*up = 0;
20225 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20226 				uint32_t sum;
20227 
20228 				/* pseudo-header checksumming */
20229 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20230 				sum = (sum & 0xFFFF) + (sum >> 16);
20231 				*up = (sum & 0xFFFF) + (sum >> 16);
20232 			} else {
20233 				/* software checksumming */
20234 				TCP_STAT(tcps, tcp_out_sw_cksum);
20235 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20236 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20237 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20238 				    cksum + IP_TCP_CSUM_COMP);
20239 				if (*up == 0)
20240 					*up = 0xFFFF;
20241 			}
20242 
20243 			/* IPv4 header checksum */
20244 			if (af == AF_INET) {
20245 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20246 					ipha->ipha_hdr_checksum = 0;
20247 				} else {
20248 					IP_HDR_CKSUM(ipha, cksum,
20249 					    ((uint32_t *)ipha)[0],
20250 					    ((uint16_t *)ipha)[4]);
20251 				}
20252 			}
20253 
20254 			if (af == AF_INET &&
20255 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20256 			    af == AF_INET6 &&
20257 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20258 				mblk_t	*mp, *mp1;
20259 				uchar_t	*hdr_rptr, *hdr_wptr;
20260 				uchar_t	*pld_rptr, *pld_wptr;
20261 
20262 				/*
20263 				 * We reconstruct a pseudo packet for the hooks
20264 				 * framework using mmd_transform_link().
20265 				 * If it is a split packet we pullup the
20266 				 * payload. FW_HOOKS expects a pkt comprising
20267 				 * of two mblks: a header and the payload.
20268 				 */
20269 				if ((mp = mmd_transform_link(pkt)) == NULL) {
20270 					TCP_STAT(tcps, tcp_mdt_allocfail);
20271 					goto legacy_send;
20272 				}
20273 
20274 				if (pkt_info->pld_cnt > 1) {
20275 					/* split payload, more than one pld */
20276 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
20277 					    NULL) {
20278 						freemsg(mp);
20279 						TCP_STAT(tcps,
20280 						    tcp_mdt_allocfail);
20281 						goto legacy_send;
20282 					}
20283 					freemsg(mp->b_cont);
20284 					mp->b_cont = mp1;
20285 				} else {
20286 					mp1 = mp->b_cont;
20287 				}
20288 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
20289 
20290 				/*
20291 				 * Remember the message offsets. This is so we
20292 				 * can detect changes when we return from the
20293 				 * FW_HOOKS callbacks.
20294 				 */
20295 				hdr_rptr = mp->b_rptr;
20296 				hdr_wptr = mp->b_wptr;
20297 				pld_rptr = mp->b_cont->b_rptr;
20298 				pld_wptr = mp->b_cont->b_wptr;
20299 
20300 				if (af == AF_INET) {
20301 					DTRACE_PROBE4(
20302 					    ip4__physical__out__start,
20303 					    ill_t *, NULL,
20304 					    ill_t *, ill,
20305 					    ipha_t *, ipha,
20306 					    mblk_t *, mp);
20307 					FW_HOOKS(
20308 					    ipst->ips_ip4_physical_out_event,
20309 					    ipst->ips_ipv4firewall_physical_out,
20310 					    NULL, ill, ipha, mp, mp, 0, ipst);
20311 					DTRACE_PROBE1(
20312 					    ip4__physical__out__end,
20313 					    mblk_t *, mp);
20314 				} else {
20315 					DTRACE_PROBE4(
20316 					    ip6__physical__out_start,
20317 					    ill_t *, NULL,
20318 					    ill_t *, ill,
20319 					    ip6_t *, ip6h,
20320 					    mblk_t *, mp);
20321 					FW_HOOKS6(
20322 					    ipst->ips_ip6_physical_out_event,
20323 					    ipst->ips_ipv6firewall_physical_out,
20324 					    NULL, ill, ip6h, mp, mp, 0, ipst);
20325 					DTRACE_PROBE1(
20326 					    ip6__physical__out__end,
20327 					    mblk_t *, mp);
20328 				}
20329 
20330 				if (mp == NULL ||
20331 				    (mp1 = mp->b_cont) == NULL ||
20332 				    mp->b_rptr != hdr_rptr ||
20333 				    mp->b_wptr != hdr_wptr ||
20334 				    mp1->b_rptr != pld_rptr ||
20335 				    mp1->b_wptr != pld_wptr ||
20336 				    mp1->b_cont != NULL) {
20337 					/*
20338 					 * We abandon multidata processing and
20339 					 * return to the normal path, either
20340 					 * when a packet is blocked, or when
20341 					 * the boundaries of header buffer or
20342 					 * payload buffer have been changed by
20343 					 * FW_HOOKS[6].
20344 					 */
20345 					if (mp != NULL)
20346 						freemsg(mp);
20347 					goto legacy_send;
20348 				}
20349 				/* Finished with the pseudo packet */
20350 				freemsg(mp);
20351 			}
20352 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
20353 			    ill, ipha, ip6h);
20354 			/* advance header offset */
20355 			cur_hdr_off += hdr_frag_sz;
20356 
20357 			obbytes += tcp->tcp_last_sent_len;
20358 			++obsegs;
20359 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20360 		    *tail_unsent > 0);
20361 
20362 		if ((*xmit_tail)->b_next == NULL) {
20363 			/*
20364 			 * Store the lbolt used for RTT estimation. We can only
20365 			 * record one timestamp per mblk so we do it when we
20366 			 * reach the end of the payload buffer. Also we only
20367 			 * take a new timestamp sample when the previous timed
20368 			 * data from the same mblk has been ack'ed.
20369 			 */
20370 			(*xmit_tail)->b_prev = local_time;
20371 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20372 		}
20373 
20374 		ASSERT(*tail_unsent >= 0);
20375 		if (*tail_unsent > 0) {
20376 			/*
20377 			 * We got here because we broke out of the above
20378 			 * loop due to of one of the following cases:
20379 			 *
20380 			 *   1. len < adjusted MSS (i.e. small),
20381 			 *   2. Sender SWS avoidance,
20382 			 *   3. max_pld is zero.
20383 			 *
20384 			 * We are done for this Multidata, so trim our
20385 			 * last payload buffer (if any) accordingly.
20386 			 */
20387 			if (md_pbuf != NULL)
20388 				md_pbuf->b_wptr -= *tail_unsent;
20389 		} else if (*usable > 0) {
20390 			*xmit_tail = (*xmit_tail)->b_cont;
20391 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20392 			    (uintptr_t)INT_MAX);
20393 			*tail_unsent = (int)MBLKL(*xmit_tail);
20394 			add_buffer = B_TRUE;
20395 		}
20396 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20397 	    (tcp_mdt_chain || max_pld > 0));
20398 
20399 	if (md_mp_head != NULL) {
20400 		/* send everything down */
20401 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20402 		    &rconfirm);
20403 	}
20404 
20405 #undef PREP_NEW_MULTIDATA
20406 #undef PREP_NEW_PBUF
20407 #undef IPVER
20408 
20409 	IRE_REFRELE(ire);
20410 	return (0);
20411 }
20412 
20413 /*
20414  * A wrapper function for sending one or more Multidata messages down to
20415  * the module below ip; this routine does not release the reference of the
20416  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20417  */
20418 static void
20419 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20420     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20421 {
20422 	uint64_t delta;
20423 	nce_t *nce;
20424 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20425 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20426 
20427 	ASSERT(ire != NULL && ill != NULL);
20428 	ASSERT(ire->ire_stq != NULL);
20429 	ASSERT(md_mp_head != NULL);
20430 	ASSERT(rconfirm != NULL);
20431 
20432 	/* adjust MIBs and IRE timestamp */
20433 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
20434 	tcp->tcp_obsegs += obsegs;
20435 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20436 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20437 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20438 
20439 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20440 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20441 	} else {
20442 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20443 	}
20444 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20445 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20446 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20447 
20448 	ire->ire_ob_pkt_count += obsegs;
20449 	if (ire->ire_ipif != NULL)
20450 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20451 	ire->ire_last_used_time = lbolt;
20452 
20453 	if ((tcp->tcp_ipversion == IPV4_VERSION &&
20454 	    ipst->ips_ip4_observe.he_interested) ||
20455 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20456 	    ipst->ips_ip6_observe.he_interested)) {
20457 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
20458 		pdesc_t *dl_pkt;
20459 		pdescinfo_t pinfo;
20460 		mblk_t *nmp;
20461 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
20462 
20463 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
20464 		    (dl_pkt != NULL);
20465 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
20466 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
20467 				continue;
20468 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
20469 			    ALL_ZONES, ill, ipst);
20470 			freemsg(nmp);
20471 		}
20472 	}
20473 
20474 	/* send it down */
20475 	putnext(ire->ire_stq, md_mp_head);
20476 
20477 	/* we're done for TCP/IPv4 */
20478 	if (tcp->tcp_ipversion == IPV4_VERSION)
20479 		return;
20480 
20481 	nce = ire->ire_nce;
20482 
20483 	ASSERT(nce != NULL);
20484 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20485 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20486 
20487 	/* reachability confirmation? */
20488 	if (*rconfirm) {
20489 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20490 		if (nce->nce_state != ND_REACHABLE) {
20491 			mutex_enter(&nce->nce_lock);
20492 			nce->nce_state = ND_REACHABLE;
20493 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20494 			mutex_exit(&nce->nce_lock);
20495 			(void) untimeout(nce->nce_timeout_id);
20496 			if (ip_debug > 2) {
20497 				/* ip1dbg */
20498 				pr_addr_dbg("tcp_multisend_data: state "
20499 				    "for %s changed to REACHABLE\n",
20500 				    AF_INET6, &ire->ire_addr_v6);
20501 			}
20502 		}
20503 		/* reset transport reachability confirmation */
20504 		*rconfirm = B_FALSE;
20505 	}
20506 
20507 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20508 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20509 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20510 
20511 	if (delta > (uint64_t)ill->ill_reachable_time) {
20512 		mutex_enter(&nce->nce_lock);
20513 		switch (nce->nce_state) {
20514 		case ND_REACHABLE:
20515 		case ND_STALE:
20516 			/*
20517 			 * ND_REACHABLE is identical to ND_STALE in this
20518 			 * specific case. If reachable time has expired for
20519 			 * this neighbor (delta is greater than reachable
20520 			 * time), conceptually, the neighbor cache is no
20521 			 * longer in REACHABLE state, but already in STALE
20522 			 * state.  So the correct transition here is to
20523 			 * ND_DELAY.
20524 			 */
20525 			nce->nce_state = ND_DELAY;
20526 			mutex_exit(&nce->nce_lock);
20527 			NDP_RESTART_TIMER(nce,
20528 			    ipst->ips_delay_first_probe_time);
20529 			if (ip_debug > 3) {
20530 				/* ip2dbg */
20531 				pr_addr_dbg("tcp_multisend_data: state "
20532 				    "for %s changed to DELAY\n",
20533 				    AF_INET6, &ire->ire_addr_v6);
20534 			}
20535 			break;
20536 		case ND_DELAY:
20537 		case ND_PROBE:
20538 			mutex_exit(&nce->nce_lock);
20539 			/* Timers have already started */
20540 			break;
20541 		case ND_UNREACHABLE:
20542 			/*
20543 			 * ndp timer has detected that this nce is
20544 			 * unreachable and initiated deleting this nce
20545 			 * and all its associated IREs. This is a race
20546 			 * where we found the ire before it was deleted
20547 			 * and have just sent out a packet using this
20548 			 * unreachable nce.
20549 			 */
20550 			mutex_exit(&nce->nce_lock);
20551 			break;
20552 		default:
20553 			ASSERT(0);
20554 		}
20555 	}
20556 }
20557 
20558 /*
20559  * Derived from tcp_send_data().
20560  */
20561 static void
20562 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20563     int num_lso_seg)
20564 {
20565 	ipha_t		*ipha;
20566 	mblk_t		*ire_fp_mp;
20567 	uint_t		ire_fp_mp_len;
20568 	uint32_t	hcksum_txflags = 0;
20569 	ipaddr_t	src;
20570 	ipaddr_t	dst;
20571 	uint32_t	cksum;
20572 	uint16_t	*up;
20573 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20574 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20575 
20576 	ASSERT(DB_TYPE(mp) == M_DATA);
20577 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20578 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20579 	ASSERT(tcp->tcp_connp != NULL);
20580 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20581 
20582 	ipha = (ipha_t *)mp->b_rptr;
20583 	src = ipha->ipha_src;
20584 	dst = ipha->ipha_dst;
20585 
20586 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
20587 
20588 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20589 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20590 	    num_lso_seg);
20591 #ifndef _BIG_ENDIAN
20592 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20593 #endif
20594 	if (tcp->tcp_snd_zcopy_aware) {
20595 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20596 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20597 			mp = tcp_zcopy_disable(tcp, mp);
20598 	}
20599 
20600 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20601 		ASSERT(ill->ill_hcksum_capab != NULL);
20602 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20603 	}
20604 
20605 	/*
20606 	 * Since the TCP checksum should be recalculated by h/w, we can just
20607 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20608 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20609 	 * The partial pseudo-header excludes TCP length, that was calculated
20610 	 * in tcp_send(), so to zero *up before further processing.
20611 	 */
20612 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20613 
20614 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20615 	*up = 0;
20616 
20617 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20618 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20619 
20620 	/*
20621 	 * Append LSO flags and mss to the mp.
20622 	 */
20623 	lso_info_set(mp, mss, HW_LSO);
20624 
20625 	ipha->ipha_fragment_offset_and_flags |=
20626 	    (uint32_t)htons(ire->ire_frag_flag);
20627 
20628 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20629 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20630 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20631 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20632 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20633 
20634 	UPDATE_OB_PKT_COUNT(ire);
20635 	ire->ire_last_used_time = lbolt;
20636 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20637 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20638 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20639 	    ntohs(ipha->ipha_length));
20640 
20641 	DTRACE_PROBE4(ip4__physical__out__start,
20642 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
20643 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
20644 	    ipst->ips_ipv4firewall_physical_out, NULL,
20645 	    ill, ipha, mp, mp, 0, ipst);
20646 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20647 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
20648 
20649 	if (mp != NULL) {
20650 		if (ipst->ips_ip4_observe.he_interested) {
20651 			zoneid_t szone;
20652 
20653 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
20654 			    ipst, ALL_ZONES);
20655 			if (ire_fp_mp_len != 0)
20656 				mp->b_rptr += ire_fp_mp_len;
20657 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
20658 			    ALL_ZONES, ill, ipst);
20659 			if (ire_fp_mp_len != 0)
20660 				mp->b_rptr -= ire_fp_mp_len;
20661 		}
20662 
20663 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
20664 	}
20665 }
20666 
20667 /*
20668  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20669  * scheme, and returns one of the following:
20670  *
20671  * -1 = failed allocation.
20672  *  0 = success; burst count reached, or usable send window is too small,
20673  *      and that we'd rather wait until later before sending again.
20674  *  1 = success; we are called from tcp_multisend(), and both usable send
20675  *      window and tail_unsent are greater than the MDT threshold, and thus
20676  *      Multidata Transmit should be used instead.
20677  */
20678 static int
20679 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20680     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20681     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20682     const int mdt_thres)
20683 {
20684 	int num_burst_seg = tcp->tcp_snd_burst;
20685 	ire_t		*ire = NULL;
20686 	ill_t		*ill = NULL;
20687 	mblk_t		*ire_fp_mp = NULL;
20688 	uint_t		ire_fp_mp_len = 0;
20689 	int		num_lso_seg = 1;
20690 	uint_t		lso_usable;
20691 	boolean_t	do_lso_send = B_FALSE;
20692 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20693 
20694 	/*
20695 	 * Check LSO capability before any further work. And the similar check
20696 	 * need to be done in for(;;) loop.
20697 	 * LSO will be deployed when therer is more than one mss of available
20698 	 * data and a burst transmission is allowed.
20699 	 */
20700 	if (tcp->tcp_lso &&
20701 	    (tcp->tcp_valid_bits == 0 ||
20702 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
20703 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20704 		/*
20705 		 * Try to find usable IRE/ILL and do basic check to the ILL.
20706 		 * Double check LSO usability before going further, since the
20707 		 * underlying interface could have been changed. In case of any
20708 		 * change of LSO capability, set tcp_ire_ill_check_done to
20709 		 * B_FALSE to force to check the ILL with the next send.
20710 		 */
20711 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
20712 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
20713 			/*
20714 			 * Enable LSO with this transmission.
20715 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
20716 			 * IRE_REFRELE(ire) should be called before return.
20717 			 */
20718 			do_lso_send = B_TRUE;
20719 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
20720 			ire_fp_mp_len = MBLKL(ire_fp_mp);
20721 			/* Round up to multiple of 4 */
20722 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
20723 		} else {
20724 			tcp->tcp_lso = B_FALSE;
20725 			tcp->tcp_ire_ill_check_done = B_FALSE;
20726 			do_lso_send = B_FALSE;
20727 			ill = NULL;
20728 		}
20729 	}
20730 
20731 	for (;;) {
20732 		struct datab	*db;
20733 		tcph_t		*tcph;
20734 		uint32_t	sum;
20735 		mblk_t		*mp, *mp1;
20736 		uchar_t		*rptr;
20737 		int		len;
20738 
20739 		/*
20740 		 * If we're called by tcp_multisend(), and the amount of
20741 		 * sendable data as well as the size of current xmit_tail
20742 		 * is beyond the MDT threshold, return to the caller and
20743 		 * let the large data transmit be done using MDT.
20744 		 */
20745 		if (*usable > 0 && *usable > mdt_thres &&
20746 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20747 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20748 			ASSERT(tcp->tcp_mdt);
20749 			return (1);	/* success; do large send */
20750 		}
20751 
20752 		if (num_burst_seg == 0)
20753 			break;		/* success; burst count reached */
20754 
20755 		/*
20756 		 * Calculate the maximum payload length we can send in *one*
20757 		 * time.
20758 		 */
20759 		if (do_lso_send) {
20760 			/*
20761 			 * Check whether need to do LSO any more.
20762 			 */
20763 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
20764 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
20765 				lso_usable = MIN(lso_usable,
20766 				    num_burst_seg * mss);
20767 
20768 				num_lso_seg = lso_usable / mss;
20769 				if (lso_usable % mss) {
20770 					num_lso_seg++;
20771 					tcp->tcp_last_sent_len = (ushort_t)
20772 					    (lso_usable % mss);
20773 				} else {
20774 					tcp->tcp_last_sent_len = (ushort_t)mss;
20775 				}
20776 			} else {
20777 				do_lso_send = B_FALSE;
20778 				num_lso_seg = 1;
20779 				lso_usable = mss;
20780 			}
20781 		}
20782 
20783 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
20784 
20785 		/*
20786 		 * Adjust num_burst_seg here.
20787 		 */
20788 		num_burst_seg -= num_lso_seg;
20789 
20790 		len = mss;
20791 		if (len > *usable) {
20792 			ASSERT(do_lso_send == B_FALSE);
20793 
20794 			len = *usable;
20795 			if (len <= 0) {
20796 				/* Terminate the loop */
20797 				break;	/* success; too small */
20798 			}
20799 			/*
20800 			 * Sender silly-window avoidance.
20801 			 * Ignore this if we are going to send a
20802 			 * zero window probe out.
20803 			 *
20804 			 * TODO: force data into microscopic window?
20805 			 *	==> (!pushed || (unsent > usable))
20806 			 */
20807 			if (len < (tcp->tcp_max_swnd >> 1) &&
20808 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20809 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20810 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20811 				/*
20812 				 * If the retransmit timer is not running
20813 				 * we start it so that we will retransmit
20814 				 * in the case when the the receiver has
20815 				 * decremented the window.
20816 				 */
20817 				if (*snxt == tcp->tcp_snxt &&
20818 				    *snxt == tcp->tcp_suna) {
20819 					/*
20820 					 * We are not supposed to send
20821 					 * anything.  So let's wait a little
20822 					 * bit longer before breaking SWS
20823 					 * avoidance.
20824 					 *
20825 					 * What should the value be?
20826 					 * Suggestion: MAX(init rexmit time,
20827 					 * tcp->tcp_rto)
20828 					 */
20829 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20830 				}
20831 				break;	/* success; too small */
20832 			}
20833 		}
20834 
20835 		tcph = tcp->tcp_tcph;
20836 
20837 		/*
20838 		 * The reason to adjust len here is that we need to set flags
20839 		 * and calculate checksum.
20840 		 */
20841 		if (do_lso_send)
20842 			len = lso_usable;
20843 
20844 		*usable -= len; /* Approximate - can be adjusted later */
20845 		if (*usable > 0)
20846 			tcph->th_flags[0] = TH_ACK;
20847 		else
20848 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20849 
20850 		/*
20851 		 * Prime pump for IP's checksumming on our behalf
20852 		 * Include the adjustment for a source route if any.
20853 		 */
20854 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20855 		sum = (sum >> 16) + (sum & 0xFFFF);
20856 		U16_TO_ABE16(sum, tcph->th_sum);
20857 
20858 		U32_TO_ABE32(*snxt, tcph->th_seq);
20859 
20860 		/*
20861 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20862 		 * set.  For the case when TCP_FSS_VALID is the only valid
20863 		 * bit (normal active close), branch off only when we think
20864 		 * that the FIN flag needs to be set.  Note for this case,
20865 		 * that (snxt + len) may not reflect the actual seg_len,
20866 		 * as len may be further reduced in tcp_xmit_mp().  If len
20867 		 * gets modified, we will end up here again.
20868 		 */
20869 		if (tcp->tcp_valid_bits != 0 &&
20870 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20871 		    ((*snxt + len) == tcp->tcp_fss))) {
20872 			uchar_t		*prev_rptr;
20873 			uint32_t	prev_snxt = tcp->tcp_snxt;
20874 
20875 			if (*tail_unsent == 0) {
20876 				ASSERT((*xmit_tail)->b_cont != NULL);
20877 				*xmit_tail = (*xmit_tail)->b_cont;
20878 				prev_rptr = (*xmit_tail)->b_rptr;
20879 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20880 				    (*xmit_tail)->b_rptr);
20881 			} else {
20882 				prev_rptr = (*xmit_tail)->b_rptr;
20883 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20884 				    *tail_unsent;
20885 			}
20886 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20887 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20888 			/* Restore tcp_snxt so we get amount sent right. */
20889 			tcp->tcp_snxt = prev_snxt;
20890 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20891 				/*
20892 				 * If the previous timestamp is still in use,
20893 				 * don't stomp on it.
20894 				 */
20895 				if ((*xmit_tail)->b_next == NULL) {
20896 					(*xmit_tail)->b_prev = local_time;
20897 					(*xmit_tail)->b_next =
20898 					    (mblk_t *)(uintptr_t)(*snxt);
20899 				}
20900 			} else
20901 				(*xmit_tail)->b_rptr = prev_rptr;
20902 
20903 			if (mp == NULL) {
20904 				if (ire != NULL)
20905 					IRE_REFRELE(ire);
20906 				return (-1);
20907 			}
20908 			mp1 = mp->b_cont;
20909 
20910 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
20911 				tcp->tcp_last_sent_len = (ushort_t)len;
20912 			while (mp1->b_cont) {
20913 				*xmit_tail = (*xmit_tail)->b_cont;
20914 				(*xmit_tail)->b_prev = local_time;
20915 				(*xmit_tail)->b_next =
20916 				    (mblk_t *)(uintptr_t)(*snxt);
20917 				mp1 = mp1->b_cont;
20918 			}
20919 			*snxt += len;
20920 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20921 			BUMP_LOCAL(tcp->tcp_obsegs);
20922 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20923 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20924 			tcp_send_data(tcp, q, mp);
20925 			continue;
20926 		}
20927 
20928 		*snxt += len;	/* Adjust later if we don't send all of len */
20929 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
20930 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
20931 
20932 		if (*tail_unsent) {
20933 			/* Are the bytes above us in flight? */
20934 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20935 			if (rptr != (*xmit_tail)->b_rptr) {
20936 				*tail_unsent -= len;
20937 				if (len <= mss) /* LSO is unusable */
20938 					tcp->tcp_last_sent_len = (ushort_t)len;
20939 				len += tcp_hdr_len;
20940 				if (tcp->tcp_ipversion == IPV4_VERSION)
20941 					tcp->tcp_ipha->ipha_length = htons(len);
20942 				else
20943 					tcp->tcp_ip6h->ip6_plen =
20944 					    htons(len -
20945 					    ((char *)&tcp->tcp_ip6h[1] -
20946 					    tcp->tcp_iphc));
20947 				mp = dupb(*xmit_tail);
20948 				if (mp == NULL) {
20949 					if (ire != NULL)
20950 						IRE_REFRELE(ire);
20951 					return (-1);	/* out_of_mem */
20952 				}
20953 				mp->b_rptr = rptr;
20954 				/*
20955 				 * If the old timestamp is no longer in use,
20956 				 * sample a new timestamp now.
20957 				 */
20958 				if ((*xmit_tail)->b_next == NULL) {
20959 					(*xmit_tail)->b_prev = local_time;
20960 					(*xmit_tail)->b_next =
20961 					    (mblk_t *)(uintptr_t)(*snxt-len);
20962 				}
20963 				goto must_alloc;
20964 			}
20965 		} else {
20966 			*xmit_tail = (*xmit_tail)->b_cont;
20967 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20968 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20969 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20970 			    (*xmit_tail)->b_rptr);
20971 		}
20972 
20973 		(*xmit_tail)->b_prev = local_time;
20974 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20975 
20976 		*tail_unsent -= len;
20977 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
20978 			tcp->tcp_last_sent_len = (ushort_t)len;
20979 
20980 		len += tcp_hdr_len;
20981 		if (tcp->tcp_ipversion == IPV4_VERSION)
20982 			tcp->tcp_ipha->ipha_length = htons(len);
20983 		else
20984 			tcp->tcp_ip6h->ip6_plen = htons(len -
20985 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20986 
20987 		mp = dupb(*xmit_tail);
20988 		if (mp == NULL) {
20989 			if (ire != NULL)
20990 				IRE_REFRELE(ire);
20991 			return (-1);	/* out_of_mem */
20992 		}
20993 
20994 		len = tcp_hdr_len;
20995 		/*
20996 		 * There are four reasons to allocate a new hdr mblk:
20997 		 *  1) The bytes above us are in use by another packet
20998 		 *  2) We don't have good alignment
20999 		 *  3) The mblk is being shared
21000 		 *  4) We don't have enough room for a header
21001 		 */
21002 		rptr = mp->b_rptr - len;
21003 		if (!OK_32PTR(rptr) ||
21004 		    ((db = mp->b_datap), db->db_ref != 2) ||
21005 		    rptr < db->db_base + ire_fp_mp_len) {
21006 			/* NOTE: we assume allocb returns an OK_32PTR */
21007 
21008 		must_alloc:;
21009 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21010 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21011 			if (mp1 == NULL) {
21012 				freemsg(mp);
21013 				if (ire != NULL)
21014 					IRE_REFRELE(ire);
21015 				return (-1);	/* out_of_mem */
21016 			}
21017 			mp1->b_cont = mp;
21018 			mp = mp1;
21019 			/* Leave room for Link Level header */
21020 			len = tcp_hdr_len;
21021 			rptr =
21022 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21023 			mp->b_wptr = &rptr[len];
21024 		}
21025 
21026 		/*
21027 		 * Fill in the header using the template header, and add
21028 		 * options such as time-stamp, ECN and/or SACK, as needed.
21029 		 */
21030 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21031 
21032 		mp->b_rptr = rptr;
21033 
21034 		if (*tail_unsent) {
21035 			int spill = *tail_unsent;
21036 
21037 			mp1 = mp->b_cont;
21038 			if (mp1 == NULL)
21039 				mp1 = mp;
21040 
21041 			/*
21042 			 * If we're a little short, tack on more mblks until
21043 			 * there is no more spillover.
21044 			 */
21045 			while (spill < 0) {
21046 				mblk_t *nmp;
21047 				int nmpsz;
21048 
21049 				nmp = (*xmit_tail)->b_cont;
21050 				nmpsz = MBLKL(nmp);
21051 
21052 				/*
21053 				 * Excess data in mblk; can we split it?
21054 				 * If MDT is enabled for the connection,
21055 				 * keep on splitting as this is a transient
21056 				 * send path.
21057 				 */
21058 				if (!do_lso_send && !tcp->tcp_mdt &&
21059 				    (spill + nmpsz > 0)) {
21060 					/*
21061 					 * Don't split if stream head was
21062 					 * told to break up larger writes
21063 					 * into smaller ones.
21064 					 */
21065 					if (tcp->tcp_maxpsz > 0)
21066 						break;
21067 
21068 					/*
21069 					 * Next mblk is less than SMSS/2
21070 					 * rounded up to nearest 64-byte;
21071 					 * let it get sent as part of the
21072 					 * next segment.
21073 					 */
21074 					if (tcp->tcp_localnet &&
21075 					    !tcp->tcp_cork &&
21076 					    (nmpsz < roundup((mss >> 1), 64)))
21077 						break;
21078 				}
21079 
21080 				*xmit_tail = nmp;
21081 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21082 				/* Stash for rtt use later */
21083 				(*xmit_tail)->b_prev = local_time;
21084 				(*xmit_tail)->b_next =
21085 				    (mblk_t *)(uintptr_t)(*snxt - len);
21086 				mp1->b_cont = dupb(*xmit_tail);
21087 				mp1 = mp1->b_cont;
21088 
21089 				spill += nmpsz;
21090 				if (mp1 == NULL) {
21091 					*tail_unsent = spill;
21092 					freemsg(mp);
21093 					if (ire != NULL)
21094 						IRE_REFRELE(ire);
21095 					return (-1);	/* out_of_mem */
21096 				}
21097 			}
21098 
21099 			/* Trim back any surplus on the last mblk */
21100 			if (spill >= 0) {
21101 				mp1->b_wptr -= spill;
21102 				*tail_unsent = spill;
21103 			} else {
21104 				/*
21105 				 * We did not send everything we could in
21106 				 * order to remain within the b_cont limit.
21107 				 */
21108 				*usable -= spill;
21109 				*snxt += spill;
21110 				tcp->tcp_last_sent_len += spill;
21111 				UPDATE_MIB(&tcps->tcps_mib,
21112 				    tcpOutDataBytes, spill);
21113 				/*
21114 				 * Adjust the checksum
21115 				 */
21116 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21117 				sum += spill;
21118 				sum = (sum >> 16) + (sum & 0xFFFF);
21119 				U16_TO_ABE16(sum, tcph->th_sum);
21120 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21121 					sum = ntohs(
21122 					    ((ipha_t *)rptr)->ipha_length) +
21123 					    spill;
21124 					((ipha_t *)rptr)->ipha_length =
21125 					    htons(sum);
21126 				} else {
21127 					sum = ntohs(
21128 					    ((ip6_t *)rptr)->ip6_plen) +
21129 					    spill;
21130 					((ip6_t *)rptr)->ip6_plen =
21131 					    htons(sum);
21132 				}
21133 				*tail_unsent = 0;
21134 			}
21135 		}
21136 		if (tcp->tcp_ip_forward_progress) {
21137 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21138 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21139 			tcp->tcp_ip_forward_progress = B_FALSE;
21140 		}
21141 
21142 		if (do_lso_send) {
21143 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21144 			    num_lso_seg);
21145 			tcp->tcp_obsegs += num_lso_seg;
21146 
21147 			TCP_STAT(tcps, tcp_lso_times);
21148 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21149 		} else {
21150 			tcp_send_data(tcp, q, mp);
21151 			BUMP_LOCAL(tcp->tcp_obsegs);
21152 		}
21153 	}
21154 
21155 	if (ire != NULL)
21156 		IRE_REFRELE(ire);
21157 	return (0);
21158 }
21159 
21160 /* Unlink and return any mblk that looks like it contains a MDT info */
21161 static mblk_t *
21162 tcp_mdt_info_mp(mblk_t *mp)
21163 {
21164 	mblk_t	*prev_mp;
21165 
21166 	for (;;) {
21167 		prev_mp = mp;
21168 		/* no more to process? */
21169 		if ((mp = mp->b_cont) == NULL)
21170 			break;
21171 
21172 		switch (DB_TYPE(mp)) {
21173 		case M_CTL:
21174 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21175 				continue;
21176 			ASSERT(prev_mp != NULL);
21177 			prev_mp->b_cont = mp->b_cont;
21178 			mp->b_cont = NULL;
21179 			return (mp);
21180 		default:
21181 			break;
21182 		}
21183 	}
21184 	return (mp);
21185 }
21186 
21187 /* MDT info update routine, called when IP notifies us about MDT */
21188 static void
21189 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21190 {
21191 	boolean_t prev_state;
21192 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21193 
21194 	/*
21195 	 * IP is telling us to abort MDT on this connection?  We know
21196 	 * this because the capability is only turned off when IP
21197 	 * encounters some pathological cases, e.g. link-layer change
21198 	 * where the new driver doesn't support MDT, or in situation
21199 	 * where MDT usage on the link-layer has been switched off.
21200 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21201 	 * if the link-layer doesn't support MDT, and if it does, it
21202 	 * will indicate that the feature is to be turned on.
21203 	 */
21204 	prev_state = tcp->tcp_mdt;
21205 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21206 	if (!tcp->tcp_mdt && !first) {
21207 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21208 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21209 		    (void *)tcp->tcp_connp));
21210 	}
21211 
21212 	/*
21213 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21214 	 * so disable MDT otherwise.  The checks are done here
21215 	 * and in tcp_wput_data().
21216 	 */
21217 	if (tcp->tcp_mdt &&
21218 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21219 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21220 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21221 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21222 		tcp->tcp_mdt = B_FALSE;
21223 
21224 	if (tcp->tcp_mdt) {
21225 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21226 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21227 			    "version (%d), expected version is %d",
21228 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21229 			tcp->tcp_mdt = B_FALSE;
21230 			return;
21231 		}
21232 
21233 		/*
21234 		 * We need the driver to be able to handle at least three
21235 		 * spans per packet in order for tcp MDT to be utilized.
21236 		 * The first is for the header portion, while the rest are
21237 		 * needed to handle a packet that straddles across two
21238 		 * virtually non-contiguous buffers; a typical tcp packet
21239 		 * therefore consists of only two spans.  Note that we take
21240 		 * a zero as "don't care".
21241 		 */
21242 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21243 		    mdt_capab->ill_mdt_span_limit < 3) {
21244 			tcp->tcp_mdt = B_FALSE;
21245 			return;
21246 		}
21247 
21248 		/* a zero means driver wants default value */
21249 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21250 		    tcps->tcps_mdt_max_pbufs);
21251 		if (tcp->tcp_mdt_max_pld == 0)
21252 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21253 
21254 		/* ensure 32-bit alignment */
21255 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21256 		    mdt_capab->ill_mdt_hdr_head), 4);
21257 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21258 		    mdt_capab->ill_mdt_hdr_tail), 4);
21259 
21260 		if (!first && !prev_state) {
21261 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21262 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21263 			    (void *)tcp->tcp_connp));
21264 		}
21265 	}
21266 }
21267 
21268 /* Unlink and return any mblk that looks like it contains a LSO info */
21269 static mblk_t *
21270 tcp_lso_info_mp(mblk_t *mp)
21271 {
21272 	mblk_t	*prev_mp;
21273 
21274 	for (;;) {
21275 		prev_mp = mp;
21276 		/* no more to process? */
21277 		if ((mp = mp->b_cont) == NULL)
21278 			break;
21279 
21280 		switch (DB_TYPE(mp)) {
21281 		case M_CTL:
21282 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21283 				continue;
21284 			ASSERT(prev_mp != NULL);
21285 			prev_mp->b_cont = mp->b_cont;
21286 			mp->b_cont = NULL;
21287 			return (mp);
21288 		default:
21289 			break;
21290 		}
21291 	}
21292 
21293 	return (mp);
21294 }
21295 
21296 /* LSO info update routine, called when IP notifies us about LSO */
21297 static void
21298 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21299 {
21300 	tcp_stack_t *tcps = tcp->tcp_tcps;
21301 
21302 	/*
21303 	 * IP is telling us to abort LSO on this connection?  We know
21304 	 * this because the capability is only turned off when IP
21305 	 * encounters some pathological cases, e.g. link-layer change
21306 	 * where the new NIC/driver doesn't support LSO, or in situation
21307 	 * where LSO usage on the link-layer has been switched off.
21308 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21309 	 * if the link-layer doesn't support LSO, and if it does, it
21310 	 * will indicate that the feature is to be turned on.
21311 	 */
21312 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21313 	TCP_STAT(tcps, tcp_lso_enabled);
21314 
21315 	/*
21316 	 * We currently only support LSO on simple TCP/IPv4,
21317 	 * so disable LSO otherwise.  The checks are done here
21318 	 * and in tcp_wput_data().
21319 	 */
21320 	if (tcp->tcp_lso &&
21321 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21322 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21323 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21324 		tcp->tcp_lso = B_FALSE;
21325 		TCP_STAT(tcps, tcp_lso_disabled);
21326 	} else {
21327 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21328 		    lso_capab->ill_lso_max);
21329 	}
21330 }
21331 
21332 static void
21333 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21334 {
21335 	conn_t *connp = tcp->tcp_connp;
21336 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21337 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21338 
21339 	ASSERT(ire != NULL);
21340 
21341 	/*
21342 	 * We may be in the fastpath here, and although we essentially do
21343 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21344 	 * we try to keep things as brief as possible.  After all, these
21345 	 * are only best-effort checks, and we do more thorough ones prior
21346 	 * to calling tcp_send()/tcp_multisend().
21347 	 */
21348 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21349 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21350 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21351 	    !(ire->ire_flags & RTF_MULTIRT) &&
21352 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21353 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21354 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21355 			/* Cache the result */
21356 			connp->conn_lso_ok = B_TRUE;
21357 
21358 			ASSERT(ill->ill_lso_capab != NULL);
21359 			if (!ill->ill_lso_capab->ill_lso_on) {
21360 				ill->ill_lso_capab->ill_lso_on = 1;
21361 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21362 				    "LSO for interface %s\n", (void *)connp,
21363 				    ill->ill_name));
21364 			}
21365 			tcp_lso_update(tcp, ill->ill_lso_capab);
21366 		} else if (ipst->ips_ip_multidata_outbound &&
21367 		    ILL_MDT_CAPABLE(ill)) {
21368 			/* Cache the result */
21369 			connp->conn_mdt_ok = B_TRUE;
21370 
21371 			ASSERT(ill->ill_mdt_capab != NULL);
21372 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21373 				ill->ill_mdt_capab->ill_mdt_on = 1;
21374 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21375 				    "MDT for interface %s\n", (void *)connp,
21376 				    ill->ill_name));
21377 			}
21378 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21379 		}
21380 	}
21381 
21382 	/*
21383 	 * The goal is to reduce the number of generated tcp segments by
21384 	 * setting the maxpsz multiplier to 0; this will have an affect on
21385 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21386 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21387 	 * of outbound segments and incoming ACKs, thus allowing for better
21388 	 * network and system performance.  In contrast the legacy behavior
21389 	 * may result in sending less than SMSS size, because the last mblk
21390 	 * for some packets may have more data than needed to make up SMSS,
21391 	 * and the legacy code refused to "split" it.
21392 	 *
21393 	 * We apply the new behavior on following situations:
21394 	 *
21395 	 *   1) Loopback connections,
21396 	 *   2) Connections in which the remote peer is not on local subnet,
21397 	 *   3) Local subnet connections over the bge interface (see below).
21398 	 *
21399 	 * Ideally, we would like this behavior to apply for interfaces other
21400 	 * than bge.  However, doing so would negatively impact drivers which
21401 	 * perform dynamic mapping and unmapping of DMA resources, which are
21402 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21403 	 * packet will be generated by tcp).  The bge driver does not suffer
21404 	 * from this, as it copies the mblks into pre-mapped buffers, and
21405 	 * therefore does not require more I/O resources than before.
21406 	 *
21407 	 * Otherwise, this behavior is present on all network interfaces when
21408 	 * the destination endpoint is non-local, since reducing the number
21409 	 * of packets in general is good for the network.
21410 	 *
21411 	 * TODO We need to remove this hard-coded conditional for bge once
21412 	 *	a better "self-tuning" mechanism, or a way to comprehend
21413 	 *	the driver transmit strategy is devised.  Until the solution
21414 	 *	is found and well understood, we live with this hack.
21415 	 */
21416 	if (!tcp_static_maxpsz &&
21417 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21418 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21419 		/* override the default value */
21420 		tcp->tcp_maxpsz = 0;
21421 
21422 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21423 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21424 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21425 	}
21426 
21427 	/* set the stream head parameters accordingly */
21428 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21429 }
21430 
21431 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21432 static void
21433 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21434 {
21435 	uchar_t	fval = *mp->b_rptr;
21436 	mblk_t	*tail;
21437 	queue_t	*q = tcp->tcp_wq;
21438 
21439 	/* TODO: How should flush interact with urgent data? */
21440 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21441 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21442 		/*
21443 		 * Flush only data that has not yet been put on the wire.  If
21444 		 * we flush data that we have already transmitted, life, as we
21445 		 * know it, may come to an end.
21446 		 */
21447 		tail = tcp->tcp_xmit_tail;
21448 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21449 		tcp->tcp_xmit_tail_unsent = 0;
21450 		tcp->tcp_unsent = 0;
21451 		if (tail->b_wptr != tail->b_rptr)
21452 			tail = tail->b_cont;
21453 		if (tail) {
21454 			mblk_t **excess = &tcp->tcp_xmit_head;
21455 			for (;;) {
21456 				mblk_t *mp1 = *excess;
21457 				if (mp1 == tail)
21458 					break;
21459 				tcp->tcp_xmit_tail = mp1;
21460 				tcp->tcp_xmit_last = mp1;
21461 				excess = &mp1->b_cont;
21462 			}
21463 			*excess = NULL;
21464 			tcp_close_mpp(&tail);
21465 			if (tcp->tcp_snd_zcopy_aware)
21466 				tcp_zcopy_notify(tcp);
21467 		}
21468 		/*
21469 		 * We have no unsent data, so unsent must be less than
21470 		 * tcp_xmit_lowater, so re-enable flow.
21471 		 */
21472 		mutex_enter(&tcp->tcp_non_sq_lock);
21473 		if (tcp->tcp_flow_stopped) {
21474 			tcp_clrqfull(tcp);
21475 		}
21476 		mutex_exit(&tcp->tcp_non_sq_lock);
21477 	}
21478 	/*
21479 	 * TODO: you can't just flush these, you have to increase rwnd for one
21480 	 * thing.  For another, how should urgent data interact?
21481 	 */
21482 	if (fval & FLUSHR) {
21483 		*mp->b_rptr = fval & ~FLUSHW;
21484 		/* XXX */
21485 		qreply(q, mp);
21486 		return;
21487 	}
21488 	freemsg(mp);
21489 }
21490 
21491 /*
21492  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21493  * messages.
21494  */
21495 static void
21496 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21497 {
21498 	mblk_t	*mp1;
21499 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
21500 	STRUCT_HANDLE(strbuf, sb);
21501 	queue_t *q = tcp->tcp_wq;
21502 	int	error;
21503 	uint_t	addrlen;
21504 
21505 	/* Make sure it is one of ours. */
21506 	switch (iocp->ioc_cmd) {
21507 	case TI_GETMYNAME:
21508 	case TI_GETPEERNAME:
21509 		break;
21510 	default:
21511 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21512 		return;
21513 	}
21514 	switch (mi_copy_state(q, mp, &mp1)) {
21515 	case -1:
21516 		return;
21517 	case MI_COPY_CASE(MI_COPY_IN, 1):
21518 		break;
21519 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21520 		/* Copy out the strbuf. */
21521 		mi_copyout(q, mp);
21522 		return;
21523 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21524 		/* All done. */
21525 		mi_copy_done(q, mp, 0);
21526 		return;
21527 	default:
21528 		mi_copy_done(q, mp, EPROTO);
21529 		return;
21530 	}
21531 	/* Check alignment of the strbuf */
21532 	if (!OK_32PTR(mp1->b_rptr)) {
21533 		mi_copy_done(q, mp, EINVAL);
21534 		return;
21535 	}
21536 
21537 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
21538 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21539 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21540 		mi_copy_done(q, mp, EINVAL);
21541 		return;
21542 	}
21543 
21544 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21545 	if (mp1 == NULL)
21546 		return;
21547 
21548 	switch (iocp->ioc_cmd) {
21549 	case TI_GETMYNAME:
21550 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
21551 		break;
21552 	case TI_GETPEERNAME:
21553 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
21554 		break;
21555 	}
21556 
21557 	if (error != 0) {
21558 		mi_copy_done(q, mp, error);
21559 	} else {
21560 		mp1->b_wptr += addrlen;
21561 		STRUCT_FSET(sb, len, addrlen);
21562 
21563 		/* Copy out the address */
21564 		mi_copyout(q, mp);
21565 	}
21566 }
21567 
21568 static void
21569 tcp_use_pure_tpi(tcp_t *tcp)
21570 {
21571 #ifdef	_ILP32
21572 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
21573 #else
21574 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21575 #endif
21576 	/*
21577 	 * Insert this socket into the acceptor hash.
21578 	 * We might need it for T_CONN_RES message
21579 	 */
21580 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21581 
21582 	tcp->tcp_issocket = B_FALSE;
21583 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
21584 }
21585 
21586 /*
21587  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21588  * messages.
21589  */
21590 /* ARGSUSED */
21591 static void
21592 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21593 {
21594 	conn_t 	*connp = (conn_t *)arg;
21595 	tcp_t	*tcp = connp->conn_tcp;
21596 	queue_t	*q = tcp->tcp_wq;
21597 	struct iocblk	*iocp;
21598 
21599 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21600 	/*
21601 	 * Try and ASSERT the minimum possible references on the
21602 	 * conn early enough. Since we are executing on write side,
21603 	 * the connection is obviously not detached and that means
21604 	 * there is a ref each for TCP and IP. Since we are behind
21605 	 * the squeue, the minimum references needed are 3. If the
21606 	 * conn is in classifier hash list, there should be an
21607 	 * extra ref for that (we check both the possibilities).
21608 	 */
21609 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21610 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21611 
21612 	iocp = (struct iocblk *)mp->b_rptr;
21613 	switch (iocp->ioc_cmd) {
21614 	case TCP_IOC_DEFAULT_Q:
21615 		/* Wants to be the default wq. */
21616 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21617 			iocp->ioc_error = EPERM;
21618 			iocp->ioc_count = 0;
21619 			mp->b_datap->db_type = M_IOCACK;
21620 			qreply(q, mp);
21621 			return;
21622 		}
21623 		tcp_def_q_set(tcp, mp);
21624 		return;
21625 	case _SIOCSOCKFALLBACK:
21626 		/*
21627 		 * Either sockmod is about to be popped and the socket
21628 		 * would now be treated as a plain stream, or a module
21629 		 * is about to be pushed so we could no longer use read-
21630 		 * side synchronous streams for fused loopback tcp.
21631 		 * Drain any queued data and disable direct sockfs
21632 		 * interface from now on.
21633 		 */
21634 		if (!tcp->tcp_issocket) {
21635 			DB_TYPE(mp) = M_IOCNAK;
21636 			iocp->ioc_error = EINVAL;
21637 		} else {
21638 			tcp_use_pure_tpi(tcp);
21639 			DB_TYPE(mp) = M_IOCACK;
21640 			iocp->ioc_error = 0;
21641 		}
21642 		iocp->ioc_count = 0;
21643 		iocp->ioc_rval = 0;
21644 		qreply(q, mp);
21645 		return;
21646 	}
21647 	CALL_IP_WPUT(connp, q, mp);
21648 }
21649 
21650 /*
21651  * This routine is called by tcp_wput() to handle all TPI requests.
21652  */
21653 /* ARGSUSED */
21654 static void
21655 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21656 {
21657 	conn_t 	*connp = (conn_t *)arg;
21658 	tcp_t	*tcp = connp->conn_tcp;
21659 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21660 	uchar_t *rptr;
21661 	t_scalar_t type;
21662 	cred_t *cr;
21663 
21664 	/*
21665 	 * Try and ASSERT the minimum possible references on the
21666 	 * conn early enough. Since we are executing on write side,
21667 	 * the connection is obviously not detached and that means
21668 	 * there is a ref each for TCP and IP. Since we are behind
21669 	 * the squeue, the minimum references needed are 3. If the
21670 	 * conn is in classifier hash list, there should be an
21671 	 * extra ref for that (we check both the possibilities).
21672 	 */
21673 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21674 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21675 
21676 	rptr = mp->b_rptr;
21677 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21678 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21679 		type = ((union T_primitives *)rptr)->type;
21680 		if (type == T_EXDATA_REQ) {
21681 			tcp_output_urgent(connp, mp, arg2);
21682 		} else if (type != T_DATA_REQ) {
21683 			goto non_urgent_data;
21684 		} else {
21685 			/* TODO: options, flags, ... from user */
21686 			/* Set length to zero for reclamation below */
21687 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21688 			freeb(mp);
21689 		}
21690 		return;
21691 	} else {
21692 		if (tcp->tcp_debug) {
21693 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21694 			    "tcp_wput_proto, dropping one...");
21695 		}
21696 		freemsg(mp);
21697 		return;
21698 	}
21699 
21700 non_urgent_data:
21701 
21702 	switch ((int)tprim->type) {
21703 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21704 		/*
21705 		 * save the kssl_ent_t from the next block, and convert this
21706 		 * back to a normal bind_req.
21707 		 */
21708 		if (mp->b_cont != NULL) {
21709 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21710 
21711 			if (tcp->tcp_kssl_ent != NULL) {
21712 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21713 				    KSSL_NO_PROXY);
21714 				tcp->tcp_kssl_ent = NULL;
21715 			}
21716 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21717 			    sizeof (kssl_ent_t));
21718 			kssl_hold_ent(tcp->tcp_kssl_ent);
21719 			freemsg(mp->b_cont);
21720 			mp->b_cont = NULL;
21721 		}
21722 		tprim->type = T_BIND_REQ;
21723 
21724 	/* FALLTHROUGH */
21725 	case O_T_BIND_REQ:	/* bind request */
21726 	case T_BIND_REQ:	/* new semantics bind request */
21727 		tcp_tpi_bind(tcp, mp);
21728 		break;
21729 	case T_UNBIND_REQ:	/* unbind request */
21730 		tcp_tpi_unbind(tcp, mp);
21731 		break;
21732 	case O_T_CONN_RES:	/* old connection response XXX */
21733 	case T_CONN_RES:	/* connection response */
21734 		tcp_tli_accept(tcp, mp);
21735 		break;
21736 	case T_CONN_REQ:	/* connection request */
21737 		tcp_tpi_connect(tcp, mp);
21738 		break;
21739 	case T_DISCON_REQ:	/* disconnect request */
21740 		tcp_disconnect(tcp, mp);
21741 		break;
21742 	case T_CAPABILITY_REQ:
21743 		tcp_capability_req(tcp, mp);	/* capability request */
21744 		break;
21745 	case T_INFO_REQ:	/* information request */
21746 		tcp_info_req(tcp, mp);
21747 		break;
21748 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21749 	case T_OPTMGMT_REQ:
21750 		/*
21751 		 * Note:  no support for snmpcom_req() through new
21752 		 * T_OPTMGMT_REQ. See comments in ip.c
21753 		 */
21754 
21755 		/*
21756 		 * All Solaris components should pass a db_credp
21757 		 * for this TPI message, hence we ASSERT.
21758 		 * But in case there is some other M_PROTO that looks
21759 		 * like a TPI message sent by some other kernel
21760 		 * component, we check and return an error.
21761 		 */
21762 		cr = msg_getcred(mp, NULL);
21763 		ASSERT(cr != NULL);
21764 		if (cr == NULL) {
21765 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
21766 			return;
21767 		}
21768 		/*
21769 		 * If EINPROGRESS is returned, the request has been queued
21770 		 * for subsequent processing by ip_restart_optmgmt(), which
21771 		 * will do the CONN_DEC_REF().
21772 		 */
21773 		CONN_INC_REF(connp);
21774 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
21775 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21776 			    B_TRUE) != EINPROGRESS) {
21777 				CONN_DEC_REF(connp);
21778 			}
21779 		} else {
21780 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
21781 			    B_TRUE) != EINPROGRESS) {
21782 				CONN_DEC_REF(connp);
21783 			}
21784 		}
21785 		break;
21786 
21787 	case T_UNITDATA_REQ:	/* unitdata request */
21788 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21789 		break;
21790 	case T_ORDREL_REQ:	/* orderly release req */
21791 		freemsg(mp);
21792 
21793 		if (tcp->tcp_fused)
21794 			tcp_unfuse(tcp);
21795 
21796 		if (tcp_xmit_end(tcp) != 0) {
21797 			/*
21798 			 * We were crossing FINs and got a reset from
21799 			 * the other side. Just ignore it.
21800 			 */
21801 			if (tcp->tcp_debug) {
21802 				(void) strlog(TCP_MOD_ID, 0, 1,
21803 				    SL_ERROR|SL_TRACE,
21804 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21805 				    "state %s",
21806 				    tcp_display(tcp, NULL,
21807 				    DISP_ADDR_AND_PORT));
21808 			}
21809 		}
21810 		break;
21811 	case T_ADDR_REQ:
21812 		tcp_addr_req(tcp, mp);
21813 		break;
21814 	default:
21815 		if (tcp->tcp_debug) {
21816 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21817 			    "tcp_wput_proto, bogus TPI msg, type %d",
21818 			    tprim->type);
21819 		}
21820 		/*
21821 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21822 		 * to recover.
21823 		 */
21824 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21825 		break;
21826 	}
21827 }
21828 
21829 /*
21830  * The TCP write service routine should never be called...
21831  */
21832 /* ARGSUSED */
21833 static void
21834 tcp_wsrv(queue_t *q)
21835 {
21836 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
21837 
21838 	TCP_STAT(tcps, tcp_wsrv_called);
21839 }
21840 
21841 /* Non overlapping byte exchanger */
21842 static void
21843 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21844 {
21845 	uchar_t	uch;
21846 
21847 	while (len-- > 0) {
21848 		uch = a[len];
21849 		a[len] = b[len];
21850 		b[len] = uch;
21851 	}
21852 }
21853 
21854 /*
21855  * Send out a control packet on the tcp connection specified.  This routine
21856  * is typically called where we need a simple ACK or RST generated.
21857  */
21858 static void
21859 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21860 {
21861 	uchar_t		*rptr;
21862 	tcph_t		*tcph;
21863 	ipha_t		*ipha = NULL;
21864 	ip6_t		*ip6h = NULL;
21865 	uint32_t	sum;
21866 	int		tcp_hdr_len;
21867 	int		tcp_ip_hdr_len;
21868 	mblk_t		*mp;
21869 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21870 
21871 	/*
21872 	 * Save sum for use in source route later.
21873 	 */
21874 	ASSERT(tcp != NULL);
21875 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21876 	tcp_hdr_len = tcp->tcp_hdr_len;
21877 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21878 
21879 	/* If a text string is passed in with the request, pass it to strlog. */
21880 	if (str != NULL && tcp->tcp_debug) {
21881 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21882 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21883 		    str, seq, ack, ctl);
21884 	}
21885 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
21886 	    BPRI_MED);
21887 	if (mp == NULL) {
21888 		return;
21889 	}
21890 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
21891 	mp->b_rptr = rptr;
21892 	mp->b_wptr = &rptr[tcp_hdr_len];
21893 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21894 
21895 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21896 		ipha = (ipha_t *)rptr;
21897 		ipha->ipha_length = htons(tcp_hdr_len);
21898 	} else {
21899 		ip6h = (ip6_t *)rptr;
21900 		ASSERT(tcp != NULL);
21901 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21902 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21903 	}
21904 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21905 	tcph->th_flags[0] = (uint8_t)ctl;
21906 	if (ctl & TH_RST) {
21907 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
21908 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
21909 		/*
21910 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21911 		 */
21912 		if (tcp->tcp_snd_ts_ok &&
21913 		    tcp->tcp_state > TCPS_SYN_SENT) {
21914 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21915 			*(mp->b_wptr) = TCPOPT_EOL;
21916 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21917 				ipha->ipha_length = htons(tcp_hdr_len -
21918 				    TCPOPT_REAL_TS_LEN);
21919 			} else {
21920 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21921 				    TCPOPT_REAL_TS_LEN);
21922 			}
21923 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21924 			sum -= TCPOPT_REAL_TS_LEN;
21925 		}
21926 	}
21927 	if (ctl & TH_ACK) {
21928 		if (tcp->tcp_snd_ts_ok) {
21929 			U32_TO_BE32(lbolt,
21930 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21931 			U32_TO_BE32(tcp->tcp_ts_recent,
21932 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21933 		}
21934 
21935 		/* Update the latest receive window size in TCP header. */
21936 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21937 		    tcph->th_win);
21938 		tcp->tcp_rack = ack;
21939 		tcp->tcp_rack_cnt = 0;
21940 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
21941 	}
21942 	BUMP_LOCAL(tcp->tcp_obsegs);
21943 	U32_TO_BE32(seq, tcph->th_seq);
21944 	U32_TO_BE32(ack, tcph->th_ack);
21945 	/*
21946 	 * Include the adjustment for a source route if any.
21947 	 */
21948 	sum = (sum >> 16) + (sum & 0xFFFF);
21949 	U16_TO_BE16(sum, tcph->th_sum);
21950 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21951 }
21952 
21953 /*
21954  * If this routine returns B_TRUE, TCP can generate a RST in response
21955  * to a segment.  If it returns B_FALSE, TCP should not respond.
21956  */
21957 static boolean_t
21958 tcp_send_rst_chk(tcp_stack_t *tcps)
21959 {
21960 	clock_t	now;
21961 
21962 	/*
21963 	 * TCP needs to protect itself from generating too many RSTs.
21964 	 * This can be a DoS attack by sending us random segments
21965 	 * soliciting RSTs.
21966 	 *
21967 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21968 	 * in each 1 second interval.  In this way, TCP still generate
21969 	 * RSTs in normal cases but when under attack, the impact is
21970 	 * limited.
21971 	 */
21972 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
21973 		now = lbolt;
21974 		/* lbolt can wrap around. */
21975 		if ((tcps->tcps_last_rst_intrvl > now) ||
21976 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
21977 		    1*SECONDS)) {
21978 			tcps->tcps_last_rst_intrvl = now;
21979 			tcps->tcps_rst_cnt = 1;
21980 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
21981 			return (B_FALSE);
21982 		}
21983 	}
21984 	return (B_TRUE);
21985 }
21986 
21987 /*
21988  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21989  */
21990 static void
21991 tcp_ip_ire_mark_advice(tcp_t *tcp)
21992 {
21993 	mblk_t *mp;
21994 	ipic_t *ipic;
21995 
21996 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21997 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21998 		    &ipic);
21999 	} else {
22000 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22001 		    &ipic);
22002 	}
22003 	if (mp == NULL)
22004 		return;
22005 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22006 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22007 }
22008 
22009 /*
22010  * Return an IP advice ioctl mblk and set ipic to be the pointer
22011  * to the advice structure.
22012  */
22013 static mblk_t *
22014 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22015 {
22016 	struct iocblk *ioc;
22017 	mblk_t *mp, *mp1;
22018 
22019 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22020 	if (mp == NULL)
22021 		return (NULL);
22022 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22023 	*ipic = (ipic_t *)mp->b_rptr;
22024 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22025 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22026 
22027 	bcopy(addr, *ipic + 1, addr_len);
22028 
22029 	(*ipic)->ipic_addr_length = addr_len;
22030 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22031 
22032 	mp1 = mkiocb(IP_IOCTL);
22033 	if (mp1 == NULL) {
22034 		freemsg(mp);
22035 		return (NULL);
22036 	}
22037 	mp1->b_cont = mp;
22038 	ioc = (struct iocblk *)mp1->b_rptr;
22039 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22040 
22041 	return (mp1);
22042 }
22043 
22044 /*
22045  * Generate a reset based on an inbound packet, connp is set by caller
22046  * when RST is in response to an unexpected inbound packet for which
22047  * there is active tcp state in the system.
22048  *
22049  * IPSEC NOTE : Try to send the reply with the same protection as it came
22050  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22051  * the packet will go out at the same level of protection as it came in by
22052  * converting the IPSEC_IN to IPSEC_OUT.
22053  */
22054 static void
22055 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22056     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22057     tcp_stack_t *tcps, conn_t *connp)
22058 {
22059 	ipha_t		*ipha = NULL;
22060 	ip6_t		*ip6h = NULL;
22061 	ushort_t	len;
22062 	tcph_t		*tcph;
22063 	int		i;
22064 	mblk_t		*ipsec_mp;
22065 	boolean_t	mctl_present;
22066 	ipic_t		*ipic;
22067 	ipaddr_t	v4addr;
22068 	in6_addr_t	v6addr;
22069 	int		addr_len;
22070 	void		*addr;
22071 	queue_t		*q = tcps->tcps_g_q;
22072 	tcp_t		*tcp;
22073 	cred_t		*cr;
22074 	pid_t		pid;
22075 	mblk_t		*nmp;
22076 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22077 
22078 	if (tcps->tcps_g_q == NULL) {
22079 		/*
22080 		 * For non-zero stackids the default queue isn't created
22081 		 * until the first open, thus there can be a need to send
22082 		 * a reset before then. But we can't do that, hence we just
22083 		 * drop the packet. Later during boot, when the default queue
22084 		 * has been setup, a retransmitted packet from the peer
22085 		 * will result in a reset.
22086 		 */
22087 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22088 		    GLOBAL_NETSTACKID);
22089 		freemsg(mp);
22090 		return;
22091 	}
22092 
22093 	if (connp != NULL)
22094 		tcp = connp->conn_tcp;
22095 	else
22096 		tcp = Q_TO_TCP(q);
22097 
22098 	if (!tcp_send_rst_chk(tcps)) {
22099 		tcps->tcps_rst_unsent++;
22100 		freemsg(mp);
22101 		return;
22102 	}
22103 
22104 	if (mp->b_datap->db_type == M_CTL) {
22105 		ipsec_mp = mp;
22106 		mp = mp->b_cont;
22107 		mctl_present = B_TRUE;
22108 	} else {
22109 		ipsec_mp = mp;
22110 		mctl_present = B_FALSE;
22111 	}
22112 
22113 	if (str && q && tcps->tcps_dbg) {
22114 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22115 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22116 		    "flags 0x%x",
22117 		    str, seq, ack, ctl);
22118 	}
22119 	if (mp->b_datap->db_ref != 1) {
22120 		mblk_t *mp1 = copyb(mp);
22121 		freemsg(mp);
22122 		mp = mp1;
22123 		if (!mp) {
22124 			if (mctl_present)
22125 				freeb(ipsec_mp);
22126 			return;
22127 		} else {
22128 			if (mctl_present) {
22129 				ipsec_mp->b_cont = mp;
22130 			} else {
22131 				ipsec_mp = mp;
22132 			}
22133 		}
22134 	} else if (mp->b_cont) {
22135 		freemsg(mp->b_cont);
22136 		mp->b_cont = NULL;
22137 	}
22138 	/*
22139 	 * We skip reversing source route here.
22140 	 * (for now we replace all IP options with EOL)
22141 	 */
22142 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22143 		ipha = (ipha_t *)mp->b_rptr;
22144 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22145 			mp->b_rptr[i] = IPOPT_EOL;
22146 		/*
22147 		 * Make sure that src address isn't flagrantly invalid.
22148 		 * Not all broadcast address checking for the src address
22149 		 * is possible, since we don't know the netmask of the src
22150 		 * addr.  No check for destination address is done, since
22151 		 * IP will not pass up a packet with a broadcast dest
22152 		 * address to TCP.  Similar checks are done below for IPv6.
22153 		 */
22154 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22155 		    CLASSD(ipha->ipha_src)) {
22156 			freemsg(ipsec_mp);
22157 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22158 			return;
22159 		}
22160 	} else {
22161 		ip6h = (ip6_t *)mp->b_rptr;
22162 
22163 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22164 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22165 			freemsg(ipsec_mp);
22166 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22167 			return;
22168 		}
22169 
22170 		/* Remove any extension headers assuming partial overlay */
22171 		if (ip_hdr_len > IPV6_HDR_LEN) {
22172 			uint8_t *to;
22173 
22174 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22175 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22176 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22177 			ip_hdr_len = IPV6_HDR_LEN;
22178 			ip6h = (ip6_t *)mp->b_rptr;
22179 			ip6h->ip6_nxt = IPPROTO_TCP;
22180 		}
22181 	}
22182 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22183 	if (tcph->th_flags[0] & TH_RST) {
22184 		freemsg(ipsec_mp);
22185 		return;
22186 	}
22187 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22188 	len = ip_hdr_len + sizeof (tcph_t);
22189 	mp->b_wptr = &mp->b_rptr[len];
22190 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22191 		ipha->ipha_length = htons(len);
22192 		/* Swap addresses */
22193 		v4addr = ipha->ipha_src;
22194 		ipha->ipha_src = ipha->ipha_dst;
22195 		ipha->ipha_dst = v4addr;
22196 		ipha->ipha_ident = 0;
22197 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22198 		addr_len = IP_ADDR_LEN;
22199 		addr = &v4addr;
22200 	} else {
22201 		/* No ip6i_t in this case */
22202 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22203 		/* Swap addresses */
22204 		v6addr = ip6h->ip6_src;
22205 		ip6h->ip6_src = ip6h->ip6_dst;
22206 		ip6h->ip6_dst = v6addr;
22207 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22208 		addr_len = IPV6_ADDR_LEN;
22209 		addr = &v6addr;
22210 	}
22211 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22212 	U32_TO_BE32(ack, tcph->th_ack);
22213 	U32_TO_BE32(seq, tcph->th_seq);
22214 	U16_TO_BE16(0, tcph->th_win);
22215 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22216 	tcph->th_flags[0] = (uint8_t)ctl;
22217 	if (ctl & TH_RST) {
22218 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22219 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22220 	}
22221 
22222 	/* IP trusts us to set up labels when required. */
22223 	if (is_system_labeled() && (cr = msg_getcred(mp, &pid)) != NULL &&
22224 	    crgetlabel(cr) != NULL) {
22225 		int err;
22226 
22227 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22228 			err = tsol_check_label(cr, &mp,
22229 			    tcp->tcp_connp->conn_mac_exempt,
22230 			    tcps->tcps_netstack->netstack_ip, pid);
22231 		else
22232 			err = tsol_check_label_v6(cr, &mp,
22233 			    tcp->tcp_connp->conn_mac_exempt,
22234 			    tcps->tcps_netstack->netstack_ip, pid);
22235 		if (mctl_present)
22236 			ipsec_mp->b_cont = mp;
22237 		else
22238 			ipsec_mp = mp;
22239 		if (err != 0) {
22240 			freemsg(ipsec_mp);
22241 			return;
22242 		}
22243 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22244 			ipha = (ipha_t *)mp->b_rptr;
22245 		} else {
22246 			ip6h = (ip6_t *)mp->b_rptr;
22247 		}
22248 	}
22249 
22250 	if (mctl_present) {
22251 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22252 
22253 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22254 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22255 			return;
22256 		}
22257 	}
22258 	if (zoneid == ALL_ZONES)
22259 		zoneid = GLOBAL_ZONEID;
22260 
22261 	/* Add the zoneid so ip_output routes it properly */
22262 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22263 		freemsg(ipsec_mp);
22264 		return;
22265 	}
22266 	ipsec_mp = nmp;
22267 
22268 	/*
22269 	 * NOTE:  one might consider tracing a TCP packet here, but
22270 	 * this function has no active TCP state and no tcp structure
22271 	 * that has a trace buffer.  If we traced here, we would have
22272 	 * to keep a local trace buffer in tcp_record_trace().
22273 	 *
22274 	 * TSol note: The mblk that contains the incoming packet was
22275 	 * reused by tcp_xmit_listener_reset, so it already contains
22276 	 * the right credentials and we don't need to call mblk_setcred.
22277 	 * Also the conn's cred is not right since it is associated
22278 	 * with tcps_g_q.
22279 	 */
22280 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22281 
22282 	/*
22283 	 * Tell IP to mark the IRE used for this destination temporary.
22284 	 * This way, we can limit our exposure to DoS attack because IP
22285 	 * creates an IRE for each destination.  If there are too many,
22286 	 * the time to do any routing lookup will be extremely long.  And
22287 	 * the lookup can be in interrupt context.
22288 	 *
22289 	 * Note that in normal circumstances, this marking should not
22290 	 * affect anything.  It would be nice if only 1 message is
22291 	 * needed to inform IP that the IRE created for this RST should
22292 	 * not be added to the cache table.  But there is currently
22293 	 * not such communication mechanism between TCP and IP.  So
22294 	 * the best we can do now is to send the advice ioctl to IP
22295 	 * to mark the IRE temporary.
22296 	 */
22297 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22298 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22299 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22300 	}
22301 }
22302 
22303 /*
22304  * Initiate closedown sequence on an active connection.  (May be called as
22305  * writer.)  Return value zero for OK return, non-zero for error return.
22306  */
22307 static int
22308 tcp_xmit_end(tcp_t *tcp)
22309 {
22310 	ipic_t	*ipic;
22311 	mblk_t	*mp;
22312 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22313 
22314 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22315 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22316 		/*
22317 		 * Invalid state, only states TCPS_SYN_RCVD,
22318 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22319 		 */
22320 		return (-1);
22321 	}
22322 
22323 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22324 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22325 	/*
22326 	 * If there is nothing more unsent, send the FIN now.
22327 	 * Otherwise, it will go out with the last segment.
22328 	 */
22329 	if (tcp->tcp_unsent == 0) {
22330 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22331 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22332 
22333 		if (mp) {
22334 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22335 		} else {
22336 			/*
22337 			 * Couldn't allocate msg.  Pretend we got it out.
22338 			 * Wait for rexmit timeout.
22339 			 */
22340 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22341 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22342 		}
22343 
22344 		/*
22345 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22346 		 * changed.
22347 		 */
22348 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22349 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22350 		}
22351 	} else {
22352 		/*
22353 		 * If tcp->tcp_cork is set, then the data will not get sent,
22354 		 * so we have to check that and unset it first.
22355 		 */
22356 		if (tcp->tcp_cork)
22357 			tcp->tcp_cork = B_FALSE;
22358 		tcp_wput_data(tcp, NULL, B_FALSE);
22359 	}
22360 
22361 	/*
22362 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22363 	 * is 0, don't update the cache.
22364 	 */
22365 	if (tcps->tcps_rtt_updates == 0 ||
22366 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22367 		return (0);
22368 
22369 	/*
22370 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22371 	 * different from the destination.
22372 	 */
22373 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22374 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22375 			return (0);
22376 		}
22377 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22378 		    &ipic);
22379 	} else {
22380 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22381 		    &tcp->tcp_ip6h->ip6_dst))) {
22382 			return (0);
22383 		}
22384 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22385 		    &ipic);
22386 	}
22387 
22388 	/* Record route attributes in the IRE for use by future connections. */
22389 	if (mp == NULL)
22390 		return (0);
22391 
22392 	/*
22393 	 * We do not have a good algorithm to update ssthresh at this time.
22394 	 * So don't do any update.
22395 	 */
22396 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22397 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22398 
22399 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22400 
22401 	return (0);
22402 }
22403 
22404 /* ARGSUSED */
22405 void
22406 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
22407 {
22408 	conn_t *connp = (conn_t *)arg;
22409 	mblk_t *mp1;
22410 	tcp_t *tcp = connp->conn_tcp;
22411 	tcp_xmit_reset_event_t *eventp;
22412 
22413 	ASSERT(mp->b_datap->db_type == M_PROTO &&
22414 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
22415 
22416 	if (tcp->tcp_state != TCPS_LISTEN) {
22417 		freemsg(mp);
22418 		return;
22419 	}
22420 
22421 	mp1 = mp->b_cont;
22422 	mp->b_cont = NULL;
22423 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
22424 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
22425 	    connp->conn_netstack);
22426 
22427 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
22428 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
22429 	freemsg(mp);
22430 }
22431 
22432 /*
22433  * Generate a "no listener here" RST in response to an "unknown" segment.
22434  * connp is set by caller when RST is in response to an unexpected
22435  * inbound packet for which there is active tcp state in the system.
22436  * Note that we are reusing the incoming mp to construct the outgoing RST.
22437  */
22438 void
22439 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22440     tcp_stack_t *tcps, conn_t *connp)
22441 {
22442 	uchar_t		*rptr;
22443 	uint32_t	seg_len;
22444 	tcph_t		*tcph;
22445 	uint32_t	seg_seq;
22446 	uint32_t	seg_ack;
22447 	uint_t		flags;
22448 	mblk_t		*ipsec_mp;
22449 	ipha_t 		*ipha;
22450 	ip6_t 		*ip6h;
22451 	boolean_t	mctl_present = B_FALSE;
22452 	boolean_t	check = B_TRUE;
22453 	boolean_t	policy_present;
22454 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22455 
22456 	TCP_STAT(tcps, tcp_no_listener);
22457 
22458 	ipsec_mp = mp;
22459 
22460 	if (mp->b_datap->db_type == M_CTL) {
22461 		ipsec_in_t *ii;
22462 
22463 		mctl_present = B_TRUE;
22464 		mp = mp->b_cont;
22465 
22466 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22467 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22468 		if (ii->ipsec_in_dont_check) {
22469 			check = B_FALSE;
22470 			if (!ii->ipsec_in_secure) {
22471 				freeb(ipsec_mp);
22472 				mctl_present = B_FALSE;
22473 				ipsec_mp = mp;
22474 			}
22475 		}
22476 	}
22477 
22478 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22479 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22480 		ipha = (ipha_t *)mp->b_rptr;
22481 		ip6h = NULL;
22482 	} else {
22483 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22484 		ipha = NULL;
22485 		ip6h = (ip6_t *)mp->b_rptr;
22486 	}
22487 
22488 	if (check && policy_present) {
22489 		/*
22490 		 * The conn_t parameter is NULL because we already know
22491 		 * nobody's home.
22492 		 */
22493 		ipsec_mp = ipsec_check_global_policy(
22494 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22495 		    tcps->tcps_netstack);
22496 		if (ipsec_mp == NULL)
22497 			return;
22498 	}
22499 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22500 		DTRACE_PROBE2(
22501 		    tx__ip__log__error__nolistener__tcp,
22502 		    char *, "Could not reply with RST to mp(1)",
22503 		    mblk_t *, mp);
22504 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22505 		freemsg(ipsec_mp);
22506 		return;
22507 	}
22508 
22509 	rptr = mp->b_rptr;
22510 
22511 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22512 	seg_seq = BE32_TO_U32(tcph->th_seq);
22513 	seg_ack = BE32_TO_U32(tcph->th_ack);
22514 	flags = tcph->th_flags[0];
22515 
22516 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22517 	if (flags & TH_RST) {
22518 		freemsg(ipsec_mp);
22519 	} else if (flags & TH_ACK) {
22520 		tcp_xmit_early_reset("no tcp, reset",
22521 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22522 		    connp);
22523 	} else {
22524 		if (flags & TH_SYN) {
22525 			seg_len++;
22526 		} else {
22527 			/*
22528 			 * Here we violate the RFC.  Note that a normal
22529 			 * TCP will never send a segment without the ACK
22530 			 * flag, except for RST or SYN segment.  This
22531 			 * segment is neither.  Just drop it on the
22532 			 * floor.
22533 			 */
22534 			freemsg(ipsec_mp);
22535 			tcps->tcps_rst_unsent++;
22536 			return;
22537 		}
22538 
22539 		tcp_xmit_early_reset("no tcp, reset/ack",
22540 		    ipsec_mp, 0, seg_seq + seg_len,
22541 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22542 	}
22543 }
22544 
22545 /*
22546  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22547  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22548  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22549  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22550  * otherwise it will dup partial mblks.)
22551  * Otherwise, an appropriate ACK packet will be generated.  This
22552  * routine is not usually called to send new data for the first time.  It
22553  * is mostly called out of the timer for retransmits, and to generate ACKs.
22554  *
22555  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22556  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22557  * of the original mblk chain will be returned in *offset and *end_mp.
22558  */
22559 mblk_t *
22560 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22561     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22562     boolean_t rexmit)
22563 {
22564 	int	data_length;
22565 	int32_t	off = 0;
22566 	uint_t	flags;
22567 	mblk_t	*mp1;
22568 	mblk_t	*mp2;
22569 	uchar_t	*rptr;
22570 	tcph_t	*tcph;
22571 	int32_t	num_sack_blk = 0;
22572 	int32_t	sack_opt_len = 0;
22573 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22574 
22575 	/* Allocate for our maximum TCP header + link-level */
22576 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22577 	    tcps->tcps_wroff_xtra, BPRI_MED);
22578 	if (!mp1)
22579 		return (NULL);
22580 	data_length = 0;
22581 
22582 	/*
22583 	 * Note that tcp_mss has been adjusted to take into account the
22584 	 * timestamp option if applicable.  Because SACK options do not
22585 	 * appear in every TCP segments and they are of variable lengths,
22586 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22587 	 * the actual segment length when we need to send a segment which
22588 	 * includes SACK options.
22589 	 */
22590 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22591 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22592 		    tcp->tcp_num_sack_blk);
22593 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22594 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22595 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22596 			max_to_send -= sack_opt_len;
22597 	}
22598 
22599 	if (offset != NULL) {
22600 		off = *offset;
22601 		/* We use offset as an indicator that end_mp is not NULL. */
22602 		*end_mp = NULL;
22603 	}
22604 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22605 		/* This could be faster with cooperation from downstream */
22606 		if (mp2 != mp1 && !sendall &&
22607 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22608 		    max_to_send)
22609 			/*
22610 			 * Don't send the next mblk since the whole mblk
22611 			 * does not fit.
22612 			 */
22613 			break;
22614 		mp2->b_cont = dupb(mp);
22615 		mp2 = mp2->b_cont;
22616 		if (!mp2) {
22617 			freemsg(mp1);
22618 			return (NULL);
22619 		}
22620 		mp2->b_rptr += off;
22621 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22622 		    (uintptr_t)INT_MAX);
22623 
22624 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22625 		if (data_length > max_to_send) {
22626 			mp2->b_wptr -= data_length - max_to_send;
22627 			data_length = max_to_send;
22628 			off = mp2->b_wptr - mp->b_rptr;
22629 			break;
22630 		} else {
22631 			off = 0;
22632 		}
22633 	}
22634 	if (offset != NULL) {
22635 		*offset = off;
22636 		*end_mp = mp;
22637 	}
22638 	if (seg_len != NULL) {
22639 		*seg_len = data_length;
22640 	}
22641 
22642 	/* Update the latest receive window size in TCP header. */
22643 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22644 	    tcp->tcp_tcph->th_win);
22645 
22646 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22647 	mp1->b_rptr = rptr;
22648 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22649 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22650 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22651 	U32_TO_ABE32(seq, tcph->th_seq);
22652 
22653 	/*
22654 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22655 	 * that this function was called from tcp_wput_data. Thus, when called
22656 	 * to retransmit data the setting of the PUSH bit may appear some
22657 	 * what random in that it might get set when it should not. This
22658 	 * should not pose any performance issues.
22659 	 */
22660 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22661 	    tcp->tcp_unsent == data_length)) {
22662 		flags = TH_ACK | TH_PUSH;
22663 	} else {
22664 		flags = TH_ACK;
22665 	}
22666 
22667 	if (tcp->tcp_ecn_ok) {
22668 		if (tcp->tcp_ecn_echo_on)
22669 			flags |= TH_ECE;
22670 
22671 		/*
22672 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22673 		 * There is no TCP flow control for non-data segments, and
22674 		 * only data segment is transmitted reliably.
22675 		 */
22676 		if (data_length > 0 && !rexmit) {
22677 			SET_ECT(tcp, rptr);
22678 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22679 				flags |= TH_CWR;
22680 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22681 			}
22682 		}
22683 	}
22684 
22685 	if (tcp->tcp_valid_bits) {
22686 		uint32_t u1;
22687 
22688 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22689 		    seq == tcp->tcp_iss) {
22690 			uchar_t	*wptr;
22691 
22692 			/*
22693 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22694 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22695 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22696 			 * our SYN is not ack'ed but the app closes this
22697 			 * TCP connection.
22698 			 */
22699 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22700 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22701 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22702 
22703 			/*
22704 			 * Tack on the MSS option.  It is always needed
22705 			 * for both active and passive open.
22706 			 *
22707 			 * MSS option value should be interface MTU - MIN
22708 			 * TCP/IP header according to RFC 793 as it means
22709 			 * the maximum segment size TCP can receive.  But
22710 			 * to get around some broken middle boxes/end hosts
22711 			 * out there, we allow the option value to be the
22712 			 * same as the MSS option size on the peer side.
22713 			 * In this way, the other side will not send
22714 			 * anything larger than they can receive.
22715 			 *
22716 			 * Note that for SYN_SENT state, the ndd param
22717 			 * tcp_use_smss_as_mss_opt has no effect as we
22718 			 * don't know the peer's MSS option value. So
22719 			 * the only case we need to take care of is in
22720 			 * SYN_RCVD state, which is done later.
22721 			 */
22722 			wptr = mp1->b_wptr;
22723 			wptr[0] = TCPOPT_MAXSEG;
22724 			wptr[1] = TCPOPT_MAXSEG_LEN;
22725 			wptr += 2;
22726 			u1 = tcp->tcp_if_mtu -
22727 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22728 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22729 			    TCP_MIN_HEADER_LENGTH;
22730 			U16_TO_BE16(u1, wptr);
22731 			mp1->b_wptr = wptr + 2;
22732 			/* Update the offset to cover the additional word */
22733 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22734 
22735 			/*
22736 			 * Note that the following way of filling in
22737 			 * TCP options are not optimal.  Some NOPs can
22738 			 * be saved.  But there is no need at this time
22739 			 * to optimize it.  When it is needed, we will
22740 			 * do it.
22741 			 */
22742 			switch (tcp->tcp_state) {
22743 			case TCPS_SYN_SENT:
22744 				flags = TH_SYN;
22745 
22746 				if (tcp->tcp_snd_ts_ok) {
22747 					uint32_t llbolt = (uint32_t)lbolt;
22748 
22749 					wptr = mp1->b_wptr;
22750 					wptr[0] = TCPOPT_NOP;
22751 					wptr[1] = TCPOPT_NOP;
22752 					wptr[2] = TCPOPT_TSTAMP;
22753 					wptr[3] = TCPOPT_TSTAMP_LEN;
22754 					wptr += 4;
22755 					U32_TO_BE32(llbolt, wptr);
22756 					wptr += 4;
22757 					ASSERT(tcp->tcp_ts_recent == 0);
22758 					U32_TO_BE32(0L, wptr);
22759 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22760 					tcph->th_offset_and_rsrvd[0] +=
22761 					    (3 << 4);
22762 				}
22763 
22764 				/*
22765 				 * Set up all the bits to tell other side
22766 				 * we are ECN capable.
22767 				 */
22768 				if (tcp->tcp_ecn_ok) {
22769 					flags |= (TH_ECE | TH_CWR);
22770 				}
22771 				break;
22772 			case TCPS_SYN_RCVD:
22773 				flags |= TH_SYN;
22774 
22775 				/*
22776 				 * Reset the MSS option value to be SMSS
22777 				 * We should probably add back the bytes
22778 				 * for timestamp option and IPsec.  We
22779 				 * don't do that as this is a workaround
22780 				 * for broken middle boxes/end hosts, it
22781 				 * is better for us to be more cautious.
22782 				 * They may not take these things into
22783 				 * account in their SMSS calculation.  Thus
22784 				 * the peer's calculated SMSS may be smaller
22785 				 * than what it can be.  This should be OK.
22786 				 */
22787 				if (tcps->tcps_use_smss_as_mss_opt) {
22788 					u1 = tcp->tcp_mss;
22789 					U16_TO_BE16(u1, wptr);
22790 				}
22791 
22792 				/*
22793 				 * If the other side is ECN capable, reply
22794 				 * that we are also ECN capable.
22795 				 */
22796 				if (tcp->tcp_ecn_ok)
22797 					flags |= TH_ECE;
22798 				break;
22799 			default:
22800 				/*
22801 				 * The above ASSERT() makes sure that this
22802 				 * must be FIN-WAIT-1 state.  Our SYN has
22803 				 * not been ack'ed so retransmit it.
22804 				 */
22805 				flags |= TH_SYN;
22806 				break;
22807 			}
22808 
22809 			if (tcp->tcp_snd_ws_ok) {
22810 				wptr = mp1->b_wptr;
22811 				wptr[0] =  TCPOPT_NOP;
22812 				wptr[1] =  TCPOPT_WSCALE;
22813 				wptr[2] =  TCPOPT_WS_LEN;
22814 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22815 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22816 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22817 			}
22818 
22819 			if (tcp->tcp_snd_sack_ok) {
22820 				wptr = mp1->b_wptr;
22821 				wptr[0] = TCPOPT_NOP;
22822 				wptr[1] = TCPOPT_NOP;
22823 				wptr[2] = TCPOPT_SACK_PERMITTED;
22824 				wptr[3] = TCPOPT_SACK_OK_LEN;
22825 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22826 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22827 			}
22828 
22829 			/* allocb() of adequate mblk assures space */
22830 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22831 			    (uintptr_t)INT_MAX);
22832 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22833 			/*
22834 			 * Get IP set to checksum on our behalf
22835 			 * Include the adjustment for a source route if any.
22836 			 */
22837 			u1 += tcp->tcp_sum;
22838 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22839 			U16_TO_BE16(u1, tcph->th_sum);
22840 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22841 		}
22842 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22843 		    (seq + data_length) == tcp->tcp_fss) {
22844 			if (!tcp->tcp_fin_acked) {
22845 				flags |= TH_FIN;
22846 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22847 			}
22848 			if (!tcp->tcp_fin_sent) {
22849 				tcp->tcp_fin_sent = B_TRUE;
22850 				switch (tcp->tcp_state) {
22851 				case TCPS_SYN_RCVD:
22852 				case TCPS_ESTABLISHED:
22853 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22854 					break;
22855 				case TCPS_CLOSE_WAIT:
22856 					tcp->tcp_state = TCPS_LAST_ACK;
22857 					break;
22858 				}
22859 				if (tcp->tcp_suna == tcp->tcp_snxt)
22860 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22861 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22862 			}
22863 		}
22864 		/*
22865 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22866 		 * is smaller than seq, u1 will become a very huge value.
22867 		 * So the comparison will fail.  Also note that tcp_urp
22868 		 * should be positive, see RFC 793 page 17.
22869 		 */
22870 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22871 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22872 		    u1 < (uint32_t)(64 * 1024)) {
22873 			flags |= TH_URG;
22874 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
22875 			U32_TO_ABE16(u1, tcph->th_urp);
22876 		}
22877 	}
22878 	tcph->th_flags[0] = (uchar_t)flags;
22879 	tcp->tcp_rack = tcp->tcp_rnxt;
22880 	tcp->tcp_rack_cnt = 0;
22881 
22882 	if (tcp->tcp_snd_ts_ok) {
22883 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22884 			uint32_t llbolt = (uint32_t)lbolt;
22885 
22886 			U32_TO_BE32(llbolt,
22887 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22888 			U32_TO_BE32(tcp->tcp_ts_recent,
22889 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22890 		}
22891 	}
22892 
22893 	if (num_sack_blk > 0) {
22894 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22895 		sack_blk_t *tmp;
22896 		int32_t	i;
22897 
22898 		wptr[0] = TCPOPT_NOP;
22899 		wptr[1] = TCPOPT_NOP;
22900 		wptr[2] = TCPOPT_SACK;
22901 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22902 		    sizeof (sack_blk_t);
22903 		wptr += TCPOPT_REAL_SACK_LEN;
22904 
22905 		tmp = tcp->tcp_sack_list;
22906 		for (i = 0; i < num_sack_blk; i++) {
22907 			U32_TO_BE32(tmp[i].begin, wptr);
22908 			wptr += sizeof (tcp_seq);
22909 			U32_TO_BE32(tmp[i].end, wptr);
22910 			wptr += sizeof (tcp_seq);
22911 		}
22912 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22913 	}
22914 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22915 	data_length += (int)(mp1->b_wptr - rptr);
22916 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22917 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22918 	} else {
22919 		ip6_t *ip6 = (ip6_t *)(rptr +
22920 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22921 		    sizeof (ip6i_t) : 0));
22922 
22923 		ip6->ip6_plen = htons(data_length -
22924 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22925 	}
22926 
22927 	/*
22928 	 * Prime pump for IP
22929 	 * Include the adjustment for a source route if any.
22930 	 */
22931 	data_length -= tcp->tcp_ip_hdr_len;
22932 	data_length += tcp->tcp_sum;
22933 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22934 	U16_TO_ABE16(data_length, tcph->th_sum);
22935 	if (tcp->tcp_ip_forward_progress) {
22936 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22937 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22938 		tcp->tcp_ip_forward_progress = B_FALSE;
22939 	}
22940 	return (mp1);
22941 }
22942 
22943 /* This function handles the push timeout. */
22944 void
22945 tcp_push_timer(void *arg)
22946 {
22947 	conn_t	*connp = (conn_t *)arg;
22948 	tcp_t *tcp = connp->conn_tcp;
22949 
22950 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
22951 
22952 	ASSERT(tcp->tcp_listener == NULL);
22953 
22954 	ASSERT(!IPCL_IS_NONSTR(connp));
22955 
22956 	tcp->tcp_push_tid = 0;
22957 
22958 	if (tcp->tcp_rcv_list != NULL &&
22959 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
22960 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22961 }
22962 
22963 /*
22964  * This function handles delayed ACK timeout.
22965  */
22966 static void
22967 tcp_ack_timer(void *arg)
22968 {
22969 	conn_t	*connp = (conn_t *)arg;
22970 	tcp_t *tcp = connp->conn_tcp;
22971 	mblk_t *mp;
22972 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22973 
22974 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
22975 
22976 	tcp->tcp_ack_tid = 0;
22977 
22978 	if (tcp->tcp_fused)
22979 		return;
22980 
22981 	/*
22982 	 * Do not send ACK if there is no outstanding unack'ed data.
22983 	 */
22984 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22985 		return;
22986 	}
22987 
22988 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22989 		/*
22990 		 * Make sure we don't allow deferred ACKs to result in
22991 		 * timer-based ACKing.  If we have held off an ACK
22992 		 * when there was more than an mss here, and the timer
22993 		 * goes off, we have to worry about the possibility
22994 		 * that the sender isn't doing slow-start, or is out
22995 		 * of step with us for some other reason.  We fall
22996 		 * permanently back in the direction of
22997 		 * ACK-every-other-packet as suggested in RFC 1122.
22998 		 */
22999 		if (tcp->tcp_rack_abs_max > 2)
23000 			tcp->tcp_rack_abs_max--;
23001 		tcp->tcp_rack_cur_max = 2;
23002 	}
23003 	mp = tcp_ack_mp(tcp);
23004 
23005 	if (mp != NULL) {
23006 		BUMP_LOCAL(tcp->tcp_obsegs);
23007 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23008 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23009 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23010 	}
23011 }
23012 
23013 
23014 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23015 static mblk_t *
23016 tcp_ack_mp(tcp_t *tcp)
23017 {
23018 	uint32_t	seq_no;
23019 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23020 
23021 	/*
23022 	 * There are a few cases to be considered while setting the sequence no.
23023 	 * Essentially, we can come here while processing an unacceptable pkt
23024 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23025 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23026 	 * If we are here for a zero window probe, stick with suna. In all
23027 	 * other cases, we check if suna + swnd encompasses snxt and set
23028 	 * the sequence number to snxt, if so. If snxt falls outside the
23029 	 * window (the receiver probably shrunk its window), we will go with
23030 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23031 	 * receiver.
23032 	 */
23033 	if (tcp->tcp_zero_win_probe) {
23034 		seq_no = tcp->tcp_suna;
23035 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23036 		ASSERT(tcp->tcp_swnd == 0);
23037 		seq_no = tcp->tcp_snxt;
23038 	} else {
23039 		seq_no = SEQ_GT(tcp->tcp_snxt,
23040 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23041 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23042 	}
23043 
23044 	if (tcp->tcp_valid_bits) {
23045 		/*
23046 		 * For the complex case where we have to send some
23047 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23048 		 */
23049 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23050 		    NULL, B_FALSE));
23051 	} else {
23052 		/* Generate a simple ACK */
23053 		int	data_length;
23054 		uchar_t	*rptr;
23055 		tcph_t	*tcph;
23056 		mblk_t	*mp1;
23057 		int32_t	tcp_hdr_len;
23058 		int32_t	tcp_tcp_hdr_len;
23059 		int32_t	num_sack_blk = 0;
23060 		int32_t sack_opt_len;
23061 
23062 		/*
23063 		 * Allocate space for TCP + IP headers
23064 		 * and link-level header
23065 		 */
23066 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23067 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23068 			    tcp->tcp_num_sack_blk);
23069 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23070 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23071 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23072 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23073 		} else {
23074 			tcp_hdr_len = tcp->tcp_hdr_len;
23075 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23076 		}
23077 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23078 		if (!mp1)
23079 			return (NULL);
23080 
23081 		/* Update the latest receive window size in TCP header. */
23082 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23083 		    tcp->tcp_tcph->th_win);
23084 		/* copy in prototype TCP + IP header */
23085 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23086 		mp1->b_rptr = rptr;
23087 		mp1->b_wptr = rptr + tcp_hdr_len;
23088 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23089 
23090 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23091 
23092 		/* Set the TCP sequence number. */
23093 		U32_TO_ABE32(seq_no, tcph->th_seq);
23094 
23095 		/* Set up the TCP flag field. */
23096 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23097 		if (tcp->tcp_ecn_echo_on)
23098 			tcph->th_flags[0] |= TH_ECE;
23099 
23100 		tcp->tcp_rack = tcp->tcp_rnxt;
23101 		tcp->tcp_rack_cnt = 0;
23102 
23103 		/* fill in timestamp option if in use */
23104 		if (tcp->tcp_snd_ts_ok) {
23105 			uint32_t llbolt = (uint32_t)lbolt;
23106 
23107 			U32_TO_BE32(llbolt,
23108 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23109 			U32_TO_BE32(tcp->tcp_ts_recent,
23110 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23111 		}
23112 
23113 		/* Fill in SACK options */
23114 		if (num_sack_blk > 0) {
23115 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23116 			sack_blk_t *tmp;
23117 			int32_t	i;
23118 
23119 			wptr[0] = TCPOPT_NOP;
23120 			wptr[1] = TCPOPT_NOP;
23121 			wptr[2] = TCPOPT_SACK;
23122 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23123 			    sizeof (sack_blk_t);
23124 			wptr += TCPOPT_REAL_SACK_LEN;
23125 
23126 			tmp = tcp->tcp_sack_list;
23127 			for (i = 0; i < num_sack_blk; i++) {
23128 				U32_TO_BE32(tmp[i].begin, wptr);
23129 				wptr += sizeof (tcp_seq);
23130 				U32_TO_BE32(tmp[i].end, wptr);
23131 				wptr += sizeof (tcp_seq);
23132 			}
23133 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23134 			    << 4);
23135 		}
23136 
23137 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23138 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23139 		} else {
23140 			/* Check for ip6i_t header in sticky hdrs */
23141 			ip6_t *ip6 = (ip6_t *)(rptr +
23142 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23143 			    sizeof (ip6i_t) : 0));
23144 
23145 			ip6->ip6_plen = htons(tcp_hdr_len -
23146 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23147 		}
23148 
23149 		/*
23150 		 * Prime pump for checksum calculation in IP.  Include the
23151 		 * adjustment for a source route if any.
23152 		 */
23153 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23154 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23155 		U16_TO_ABE16(data_length, tcph->th_sum);
23156 
23157 		if (tcp->tcp_ip_forward_progress) {
23158 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23159 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23160 			tcp->tcp_ip_forward_progress = B_FALSE;
23161 		}
23162 		return (mp1);
23163 	}
23164 }
23165 
23166 /*
23167  * Hash list insertion routine for tcp_t structures. Each hash bucket
23168  * contains a list of tcp_t entries, and each entry is bound to a unique
23169  * port. If there are multiple tcp_t's that are bound to the same port, then
23170  * one of them will be linked into the hash bucket list, and the rest will
23171  * hang off of that one entry. For each port, entries bound to a specific IP
23172  * address will be inserted before those those bound to INADDR_ANY.
23173  */
23174 static void
23175 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23176 {
23177 	tcp_t	**tcpp;
23178 	tcp_t	*tcpnext;
23179 	tcp_t	*tcphash;
23180 
23181 	if (tcp->tcp_ptpbhn != NULL) {
23182 		ASSERT(!caller_holds_lock);
23183 		tcp_bind_hash_remove(tcp);
23184 	}
23185 	tcpp = &tbf->tf_tcp;
23186 	if (!caller_holds_lock) {
23187 		mutex_enter(&tbf->tf_lock);
23188 	} else {
23189 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23190 	}
23191 	tcphash = tcpp[0];
23192 	tcpnext = NULL;
23193 	if (tcphash != NULL) {
23194 		/* Look for an entry using the same port */
23195 		while ((tcphash = tcpp[0]) != NULL &&
23196 		    tcp->tcp_lport != tcphash->tcp_lport)
23197 			tcpp = &(tcphash->tcp_bind_hash);
23198 
23199 		/* The port was not found, just add to the end */
23200 		if (tcphash == NULL)
23201 			goto insert;
23202 
23203 		/*
23204 		 * OK, there already exists an entry bound to the
23205 		 * same port.
23206 		 *
23207 		 * If the new tcp bound to the INADDR_ANY address
23208 		 * and the first one in the list is not bound to
23209 		 * INADDR_ANY we skip all entries until we find the
23210 		 * first one bound to INADDR_ANY.
23211 		 * This makes sure that applications binding to a
23212 		 * specific address get preference over those binding to
23213 		 * INADDR_ANY.
23214 		 */
23215 		tcpnext = tcphash;
23216 		tcphash = NULL;
23217 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23218 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23219 			while ((tcpnext = tcpp[0]) != NULL &&
23220 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23221 				tcpp = &(tcpnext->tcp_bind_hash_port);
23222 
23223 			if (tcpnext) {
23224 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23225 				tcphash = tcpnext->tcp_bind_hash;
23226 				if (tcphash != NULL) {
23227 					tcphash->tcp_ptpbhn =
23228 					    &(tcp->tcp_bind_hash);
23229 					tcpnext->tcp_bind_hash = NULL;
23230 				}
23231 			}
23232 		} else {
23233 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23234 			tcphash = tcpnext->tcp_bind_hash;
23235 			if (tcphash != NULL) {
23236 				tcphash->tcp_ptpbhn =
23237 				    &(tcp->tcp_bind_hash);
23238 				tcpnext->tcp_bind_hash = NULL;
23239 			}
23240 		}
23241 	}
23242 insert:
23243 	tcp->tcp_bind_hash_port = tcpnext;
23244 	tcp->tcp_bind_hash = tcphash;
23245 	tcp->tcp_ptpbhn = tcpp;
23246 	tcpp[0] = tcp;
23247 	if (!caller_holds_lock)
23248 		mutex_exit(&tbf->tf_lock);
23249 }
23250 
23251 /*
23252  * Hash list removal routine for tcp_t structures.
23253  */
23254 static void
23255 tcp_bind_hash_remove(tcp_t *tcp)
23256 {
23257 	tcp_t	*tcpnext;
23258 	kmutex_t *lockp;
23259 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23260 
23261 	if (tcp->tcp_ptpbhn == NULL)
23262 		return;
23263 
23264 	/*
23265 	 * Extract the lock pointer in case there are concurrent
23266 	 * hash_remove's for this instance.
23267 	 */
23268 	ASSERT(tcp->tcp_lport != 0);
23269 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23270 
23271 	ASSERT(lockp != NULL);
23272 	mutex_enter(lockp);
23273 	if (tcp->tcp_ptpbhn) {
23274 		tcpnext = tcp->tcp_bind_hash_port;
23275 		if (tcpnext != NULL) {
23276 			tcp->tcp_bind_hash_port = NULL;
23277 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23278 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23279 			if (tcpnext->tcp_bind_hash != NULL) {
23280 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23281 				    &(tcpnext->tcp_bind_hash);
23282 				tcp->tcp_bind_hash = NULL;
23283 			}
23284 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23285 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23286 			tcp->tcp_bind_hash = NULL;
23287 		}
23288 		*tcp->tcp_ptpbhn = tcpnext;
23289 		tcp->tcp_ptpbhn = NULL;
23290 	}
23291 	mutex_exit(lockp);
23292 }
23293 
23294 
23295 /*
23296  * Hash list lookup routine for tcp_t structures.
23297  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23298  */
23299 static tcp_t *
23300 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23301 {
23302 	tf_t	*tf;
23303 	tcp_t	*tcp;
23304 
23305 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23306 	mutex_enter(&tf->tf_lock);
23307 	for (tcp = tf->tf_tcp; tcp != NULL;
23308 	    tcp = tcp->tcp_acceptor_hash) {
23309 		if (tcp->tcp_acceptor_id == id) {
23310 			CONN_INC_REF(tcp->tcp_connp);
23311 			mutex_exit(&tf->tf_lock);
23312 			return (tcp);
23313 		}
23314 	}
23315 	mutex_exit(&tf->tf_lock);
23316 	return (NULL);
23317 }
23318 
23319 
23320 /*
23321  * Hash list insertion routine for tcp_t structures.
23322  */
23323 void
23324 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23325 {
23326 	tf_t	*tf;
23327 	tcp_t	**tcpp;
23328 	tcp_t	*tcpnext;
23329 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23330 
23331 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23332 
23333 	if (tcp->tcp_ptpahn != NULL)
23334 		tcp_acceptor_hash_remove(tcp);
23335 	tcpp = &tf->tf_tcp;
23336 	mutex_enter(&tf->tf_lock);
23337 	tcpnext = tcpp[0];
23338 	if (tcpnext)
23339 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23340 	tcp->tcp_acceptor_hash = tcpnext;
23341 	tcp->tcp_ptpahn = tcpp;
23342 	tcpp[0] = tcp;
23343 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23344 	mutex_exit(&tf->tf_lock);
23345 }
23346 
23347 /*
23348  * Hash list removal routine for tcp_t structures.
23349  */
23350 static void
23351 tcp_acceptor_hash_remove(tcp_t *tcp)
23352 {
23353 	tcp_t	*tcpnext;
23354 	kmutex_t *lockp;
23355 
23356 	/*
23357 	 * Extract the lock pointer in case there are concurrent
23358 	 * hash_remove's for this instance.
23359 	 */
23360 	lockp = tcp->tcp_acceptor_lockp;
23361 
23362 	if (tcp->tcp_ptpahn == NULL)
23363 		return;
23364 
23365 	ASSERT(lockp != NULL);
23366 	mutex_enter(lockp);
23367 	if (tcp->tcp_ptpahn) {
23368 		tcpnext = tcp->tcp_acceptor_hash;
23369 		if (tcpnext) {
23370 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23371 			tcp->tcp_acceptor_hash = NULL;
23372 		}
23373 		*tcp->tcp_ptpahn = tcpnext;
23374 		tcp->tcp_ptpahn = NULL;
23375 	}
23376 	mutex_exit(lockp);
23377 	tcp->tcp_acceptor_lockp = NULL;
23378 }
23379 
23380 /*
23381  * Type three generator adapted from the random() function in 4.4 BSD:
23382  */
23383 
23384 /*
23385  * Copyright (c) 1983, 1993
23386  *	The Regents of the University of California.  All rights reserved.
23387  *
23388  * Redistribution and use in source and binary forms, with or without
23389  * modification, are permitted provided that the following conditions
23390  * are met:
23391  * 1. Redistributions of source code must retain the above copyright
23392  *    notice, this list of conditions and the following disclaimer.
23393  * 2. Redistributions in binary form must reproduce the above copyright
23394  *    notice, this list of conditions and the following disclaimer in the
23395  *    documentation and/or other materials provided with the distribution.
23396  * 3. All advertising materials mentioning features or use of this software
23397  *    must display the following acknowledgement:
23398  *	This product includes software developed by the University of
23399  *	California, Berkeley and its contributors.
23400  * 4. Neither the name of the University nor the names of its contributors
23401  *    may be used to endorse or promote products derived from this software
23402  *    without specific prior written permission.
23403  *
23404  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23405  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23406  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23407  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23408  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23409  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23410  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23411  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23412  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23413  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23414  * SUCH DAMAGE.
23415  */
23416 
23417 /* Type 3 -- x**31 + x**3 + 1 */
23418 #define	DEG_3		31
23419 #define	SEP_3		3
23420 
23421 
23422 /* Protected by tcp_random_lock */
23423 static int tcp_randtbl[DEG_3 + 1];
23424 
23425 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23426 static int *tcp_random_rptr = &tcp_randtbl[1];
23427 
23428 static int *tcp_random_state = &tcp_randtbl[1];
23429 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23430 
23431 kmutex_t tcp_random_lock;
23432 
23433 void
23434 tcp_random_init(void)
23435 {
23436 	int i;
23437 	hrtime_t hrt;
23438 	time_t wallclock;
23439 	uint64_t result;
23440 
23441 	/*
23442 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23443 	 * a longlong, which may contain resolution down to nanoseconds.
23444 	 * The current time will either be a 32-bit or a 64-bit quantity.
23445 	 * XOR the two together in a 64-bit result variable.
23446 	 * Convert the result to a 32-bit value by multiplying the high-order
23447 	 * 32-bits by the low-order 32-bits.
23448 	 */
23449 
23450 	hrt = gethrtime();
23451 	(void) drv_getparm(TIME, &wallclock);
23452 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23453 	mutex_enter(&tcp_random_lock);
23454 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23455 	    (result & 0xffffffff);
23456 
23457 	for (i = 1; i < DEG_3; i++)
23458 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23459 		    + 12345;
23460 	tcp_random_fptr = &tcp_random_state[SEP_3];
23461 	tcp_random_rptr = &tcp_random_state[0];
23462 	mutex_exit(&tcp_random_lock);
23463 	for (i = 0; i < 10 * DEG_3; i++)
23464 		(void) tcp_random();
23465 }
23466 
23467 /*
23468  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23469  * This range is selected to be approximately centered on TCP_ISS / 2,
23470  * and easy to compute. We get this value by generating a 32-bit random
23471  * number, selecting out the high-order 17 bits, and then adding one so
23472  * that we never return zero.
23473  */
23474 int
23475 tcp_random(void)
23476 {
23477 	int i;
23478 
23479 	mutex_enter(&tcp_random_lock);
23480 	*tcp_random_fptr += *tcp_random_rptr;
23481 
23482 	/*
23483 	 * The high-order bits are more random than the low-order bits,
23484 	 * so we select out the high-order 17 bits and add one so that
23485 	 * we never return zero.
23486 	 */
23487 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23488 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23489 		tcp_random_fptr = tcp_random_state;
23490 		++tcp_random_rptr;
23491 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23492 		tcp_random_rptr = tcp_random_state;
23493 
23494 	mutex_exit(&tcp_random_lock);
23495 	return (i);
23496 }
23497 
23498 static int
23499 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23500     int *t_errorp, int *sys_errorp)
23501 {
23502 	int error;
23503 	int is_absreq_failure;
23504 	t_scalar_t *opt_lenp;
23505 	t_scalar_t opt_offset;
23506 	int prim_type;
23507 	struct T_conn_req *tcreqp;
23508 	struct T_conn_res *tcresp;
23509 	cred_t *cr;
23510 
23511 	/*
23512 	 * All Solaris components should pass a db_credp
23513 	 * for this TPI message, hence we ASSERT.
23514 	 * But in case there is some other M_PROTO that looks
23515 	 * like a TPI message sent by some other kernel
23516 	 * component, we check and return an error.
23517 	 */
23518 	cr = msg_getcred(mp, NULL);
23519 	ASSERT(cr != NULL);
23520 	if (cr == NULL)
23521 		return (-1);
23522 
23523 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23524 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23525 	    prim_type == T_CONN_RES);
23526 
23527 	switch (prim_type) {
23528 	case T_CONN_REQ:
23529 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23530 		opt_offset = tcreqp->OPT_offset;
23531 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23532 		break;
23533 	case O_T_CONN_RES:
23534 	case T_CONN_RES:
23535 		tcresp = (struct T_conn_res *)mp->b_rptr;
23536 		opt_offset = tcresp->OPT_offset;
23537 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23538 		break;
23539 	}
23540 
23541 	*t_errorp = 0;
23542 	*sys_errorp = 0;
23543 	*do_disconnectp = 0;
23544 
23545 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23546 	    opt_offset, cr, &tcp_opt_obj,
23547 	    NULL, &is_absreq_failure);
23548 
23549 	switch (error) {
23550 	case  0:		/* no error */
23551 		ASSERT(is_absreq_failure == 0);
23552 		return (0);
23553 	case ENOPROTOOPT:
23554 		*t_errorp = TBADOPT;
23555 		break;
23556 	case EACCES:
23557 		*t_errorp = TACCES;
23558 		break;
23559 	default:
23560 		*t_errorp = TSYSERR; *sys_errorp = error;
23561 		break;
23562 	}
23563 	if (is_absreq_failure != 0) {
23564 		/*
23565 		 * The connection request should get the local ack
23566 		 * T_OK_ACK and then a T_DISCON_IND.
23567 		 */
23568 		*do_disconnectp = 1;
23569 	}
23570 	return (-1);
23571 }
23572 
23573 /*
23574  * Split this function out so that if the secret changes, I'm okay.
23575  *
23576  * Initialize the tcp_iss_cookie and tcp_iss_key.
23577  */
23578 
23579 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23580 
23581 static void
23582 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
23583 {
23584 	struct {
23585 		int32_t current_time;
23586 		uint32_t randnum;
23587 		uint16_t pad;
23588 		uint8_t ether[6];
23589 		uint8_t passwd[PASSWD_SIZE];
23590 	} tcp_iss_cookie;
23591 	time_t t;
23592 
23593 	/*
23594 	 * Start with the current absolute time.
23595 	 */
23596 	(void) drv_getparm(TIME, &t);
23597 	tcp_iss_cookie.current_time = t;
23598 
23599 	/*
23600 	 * XXX - Need a more random number per RFC 1750, not this crap.
23601 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23602 	 */
23603 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23604 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23605 
23606 	/*
23607 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23608 	 * as a good template.
23609 	 */
23610 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23611 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23612 
23613 	/*
23614 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23615 	 */
23616 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23617 
23618 	/*
23619 	 * See 4010593 if this section becomes a problem again,
23620 	 * but the local ethernet address is useful here.
23621 	 */
23622 	(void) localetheraddr(NULL,
23623 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23624 
23625 	/*
23626 	 * Hash 'em all together.  The MD5Final is called per-connection.
23627 	 */
23628 	mutex_enter(&tcps->tcps_iss_key_lock);
23629 	MD5Init(&tcps->tcps_iss_key);
23630 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
23631 	    sizeof (tcp_iss_cookie));
23632 	mutex_exit(&tcps->tcps_iss_key_lock);
23633 }
23634 
23635 /*
23636  * Set the RFC 1948 pass phrase
23637  */
23638 /* ARGSUSED */
23639 static int
23640 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23641     cred_t *cr)
23642 {
23643 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23644 
23645 	/*
23646 	 * Basically, value contains a new pass phrase.  Pass it along!
23647 	 */
23648 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
23649 	return (0);
23650 }
23651 
23652 /* ARGSUSED */
23653 static int
23654 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23655 {
23656 	bzero(buf, sizeof (tcp_sack_info_t));
23657 	return (0);
23658 }
23659 
23660 /* ARGSUSED */
23661 static int
23662 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23663 {
23664 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23665 	return (0);
23666 }
23667 
23668 /*
23669  * Make sure we wait until the default queue is setup, yet allow
23670  * tcp_g_q_create() to open a TCP stream.
23671  * We need to allow tcp_g_q_create() do do an open
23672  * of tcp, hence we compare curhread.
23673  * All others have to wait until the tcps_g_q has been
23674  * setup.
23675  */
23676 void
23677 tcp_g_q_setup(tcp_stack_t *tcps)
23678 {
23679 	mutex_enter(&tcps->tcps_g_q_lock);
23680 	if (tcps->tcps_g_q != NULL) {
23681 		mutex_exit(&tcps->tcps_g_q_lock);
23682 		return;
23683 	}
23684 	if (tcps->tcps_g_q_creator == NULL) {
23685 		/* This thread will set it up */
23686 		tcps->tcps_g_q_creator = curthread;
23687 		mutex_exit(&tcps->tcps_g_q_lock);
23688 		tcp_g_q_create(tcps);
23689 		mutex_enter(&tcps->tcps_g_q_lock);
23690 		ASSERT(tcps->tcps_g_q_creator == curthread);
23691 		tcps->tcps_g_q_creator = NULL;
23692 		cv_signal(&tcps->tcps_g_q_cv);
23693 		ASSERT(tcps->tcps_g_q != NULL);
23694 		mutex_exit(&tcps->tcps_g_q_lock);
23695 		return;
23696 	}
23697 	/* Everybody but the creator has to wait */
23698 	if (tcps->tcps_g_q_creator != curthread) {
23699 		while (tcps->tcps_g_q == NULL)
23700 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
23701 	}
23702 	mutex_exit(&tcps->tcps_g_q_lock);
23703 }
23704 
23705 #define	IP	"ip"
23706 
23707 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
23708 
23709 /*
23710  * Create a default tcp queue here instead of in strplumb
23711  */
23712 void
23713 tcp_g_q_create(tcp_stack_t *tcps)
23714 {
23715 	int error;
23716 	ldi_handle_t	lh = NULL;
23717 	ldi_ident_t	li = NULL;
23718 	int		rval;
23719 	cred_t		*cr;
23720 	major_t IP_MAJ;
23721 
23722 #ifdef NS_DEBUG
23723 	(void) printf("tcp_g_q_create()\n");
23724 #endif
23725 
23726 	IP_MAJ = ddi_name_to_major(IP);
23727 
23728 	ASSERT(tcps->tcps_g_q_creator == curthread);
23729 
23730 	error = ldi_ident_from_major(IP_MAJ, &li);
23731 	if (error) {
23732 #ifdef DEBUG
23733 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
23734 		    error);
23735 #endif
23736 		return;
23737 	}
23738 
23739 	cr = zone_get_kcred(netstackid_to_zoneid(
23740 	    tcps->tcps_netstack->netstack_stackid));
23741 	ASSERT(cr != NULL);
23742 	/*
23743 	 * We set the tcp default queue to IPv6 because IPv4 falls
23744 	 * back to IPv6 when it can't find a client, but
23745 	 * IPv6 does not fall back to IPv4.
23746 	 */
23747 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
23748 	if (error) {
23749 #ifdef DEBUG
23750 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
23751 		    error);
23752 #endif
23753 		goto out;
23754 	}
23755 
23756 	/*
23757 	 * This ioctl causes the tcp framework to cache a pointer to
23758 	 * this stream, so we don't want to close the stream after
23759 	 * this operation.
23760 	 * Use the kernel credentials that are for the zone we're in.
23761 	 */
23762 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
23763 	    (intptr_t)0, FKIOCTL, cr, &rval);
23764 	if (error) {
23765 #ifdef DEBUG
23766 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
23767 		    "error %d\n", error);
23768 #endif
23769 		goto out;
23770 	}
23771 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
23772 	lh = NULL;
23773 out:
23774 	/* Close layered handles */
23775 	if (li)
23776 		ldi_ident_release(li);
23777 	/* Keep cred around until _inactive needs it */
23778 	tcps->tcps_g_q_cr = cr;
23779 }
23780 
23781 /*
23782  * We keep tcp_g_q set until all other tcp_t's in the zone
23783  * has gone away, and then when tcp_g_q_inactive() is called
23784  * we clear it.
23785  */
23786 void
23787 tcp_g_q_destroy(tcp_stack_t *tcps)
23788 {
23789 #ifdef NS_DEBUG
23790 	(void) printf("tcp_g_q_destroy()for stack %d\n",
23791 	    tcps->tcps_netstack->netstack_stackid);
23792 #endif
23793 
23794 	if (tcps->tcps_g_q == NULL) {
23795 		return;	/* Nothing to cleanup */
23796 	}
23797 	/*
23798 	 * Drop reference corresponding to the default queue.
23799 	 * This reference was added from tcp_open when the default queue
23800 	 * was created, hence we compensate for this extra drop in
23801 	 * tcp_g_q_close. If the refcnt drops to zero here it means
23802 	 * the default queue was the last one to be open, in which
23803 	 * case, then tcp_g_q_inactive will be
23804 	 * called as a result of the refrele.
23805 	 */
23806 	TCPS_REFRELE(tcps);
23807 }
23808 
23809 /*
23810  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23811  * Run by tcp_q_q_inactive using a taskq.
23812  */
23813 static void
23814 tcp_g_q_close(void *arg)
23815 {
23816 	tcp_stack_t *tcps = arg;
23817 	int error;
23818 	ldi_handle_t	lh = NULL;
23819 	ldi_ident_t	li = NULL;
23820 	cred_t		*cr;
23821 	major_t IP_MAJ;
23822 
23823 	IP_MAJ = ddi_name_to_major(IP);
23824 
23825 #ifdef NS_DEBUG
23826 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
23827 	    tcps->tcps_netstack->netstack_stackid,
23828 	    tcps->tcps_netstack->netstack_refcnt);
23829 #endif
23830 	lh = tcps->tcps_g_q_lh;
23831 	if (lh == NULL)
23832 		return;	/* Nothing to cleanup */
23833 
23834 	ASSERT(tcps->tcps_refcnt == 1);
23835 	ASSERT(tcps->tcps_g_q != NULL);
23836 
23837 	error = ldi_ident_from_major(IP_MAJ, &li);
23838 	if (error) {
23839 #ifdef DEBUG
23840 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
23841 		    error);
23842 #endif
23843 		return;
23844 	}
23845 
23846 	cr = tcps->tcps_g_q_cr;
23847 	tcps->tcps_g_q_cr = NULL;
23848 	ASSERT(cr != NULL);
23849 
23850 	/*
23851 	 * Make sure we can break the recursion when tcp_close decrements
23852 	 * the reference count causing g_q_inactive to be called again.
23853 	 */
23854 	tcps->tcps_g_q_lh = NULL;
23855 
23856 	/* close the default queue */
23857 	(void) ldi_close(lh, FREAD|FWRITE, cr);
23858 	/*
23859 	 * At this point in time tcps and the rest of netstack_t might
23860 	 * have been deleted.
23861 	 */
23862 	tcps = NULL;
23863 
23864 	/* Close layered handles */
23865 	ldi_ident_release(li);
23866 	crfree(cr);
23867 }
23868 
23869 /*
23870  * Called when last tcp_t drops reference count using TCPS_REFRELE.
23871  *
23872  * Have to ensure that the ldi routines are not used by an
23873  * interrupt thread by using a taskq.
23874  */
23875 void
23876 tcp_g_q_inactive(tcp_stack_t *tcps)
23877 {
23878 	if (tcps->tcps_g_q_lh == NULL)
23879 		return;	/* Nothing to cleanup */
23880 
23881 	ASSERT(tcps->tcps_refcnt == 0);
23882 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
23883 
23884 	if (servicing_interrupt()) {
23885 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
23886 		    (void *) tcps, TQ_SLEEP);
23887 	} else {
23888 		tcp_g_q_close(tcps);
23889 	}
23890 }
23891 
23892 /*
23893  * Called by IP when IP is loaded into the kernel
23894  */
23895 void
23896 tcp_ddi_g_init(void)
23897 {
23898 	tcp_timercache = kmem_cache_create("tcp_timercache",
23899 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23900 	    NULL, NULL, NULL, NULL, NULL, 0);
23901 
23902 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23903 	    sizeof (tcp_sack_info_t), 0,
23904 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23905 
23906 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23907 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23908 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23909 
23910 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23911 
23912 	/* Initialize the random number generator */
23913 	tcp_random_init();
23914 
23915 	/* A single callback independently of how many netstacks we have */
23916 	ip_squeue_init(tcp_squeue_add);
23917 
23918 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
23919 
23920 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
23921 	    TASKQ_PREPOPULATE);
23922 
23923 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
23924 
23925 	/*
23926 	 * We want to be informed each time a stack is created or
23927 	 * destroyed in the kernel, so we can maintain the
23928 	 * set of tcp_stack_t's.
23929 	 */
23930 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
23931 	    tcp_stack_fini);
23932 }
23933 
23934 
23935 #define	INET_NAME	"ip"
23936 
23937 /*
23938  * Initialize the TCP stack instance.
23939  */
23940 static void *
23941 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
23942 {
23943 	tcp_stack_t	*tcps;
23944 	tcpparam_t	*pa;
23945 	int		i;
23946 	int		error = 0;
23947 	major_t		major;
23948 
23949 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
23950 	tcps->tcps_netstack = ns;
23951 
23952 	/* Initialize locks */
23953 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23954 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
23955 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23956 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23957 
23958 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
23959 	tcps->tcps_g_epriv_ports[0] = 2049;
23960 	tcps->tcps_g_epriv_ports[1] = 4045;
23961 	tcps->tcps_min_anonpriv_port = 512;
23962 
23963 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
23964 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
23965 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
23966 	    TCP_FANOUT_SIZE, KM_SLEEP);
23967 
23968 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
23969 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
23970 		    MUTEX_DEFAULT, NULL);
23971 	}
23972 
23973 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
23974 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
23975 		    MUTEX_DEFAULT, NULL);
23976 	}
23977 
23978 	/* TCP's IPsec code calls the packet dropper. */
23979 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
23980 
23981 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
23982 	tcps->tcps_params = pa;
23983 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
23984 
23985 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
23986 	    A_CNT(lcl_tcp_param_arr), tcps);
23987 
23988 	/*
23989 	 * Note: To really walk the device tree you need the devinfo
23990 	 * pointer to your device which is only available after probe/attach.
23991 	 * The following is safe only because it uses ddi_root_node()
23992 	 */
23993 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23994 	    tcp_opt_obj.odb_opt_arr_cnt);
23995 
23996 	/*
23997 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23998 	 * by the boot scripts.
23999 	 *
24000 	 * Use NULL name, as the name is caught by the new lockstats.
24001 	 *
24002 	 * Initialize with some random, non-guessable string, like the global
24003 	 * T_INFO_ACK.
24004 	 */
24005 
24006 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24007 	    sizeof (tcp_g_t_info_ack), tcps);
24008 
24009 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24010 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24011 
24012 	major = mod_name_to_major(INET_NAME);
24013 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24014 	ASSERT(error == 0);
24015 	return (tcps);
24016 }
24017 
24018 /*
24019  * Called when the IP module is about to be unloaded.
24020  */
24021 void
24022 tcp_ddi_g_destroy(void)
24023 {
24024 	tcp_g_kstat_fini(tcp_g_kstat);
24025 	tcp_g_kstat = NULL;
24026 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24027 
24028 	mutex_destroy(&tcp_random_lock);
24029 
24030 	kmem_cache_destroy(tcp_timercache);
24031 	kmem_cache_destroy(tcp_sack_info_cache);
24032 	kmem_cache_destroy(tcp_iphc_cache);
24033 
24034 	netstack_unregister(NS_TCP);
24035 	taskq_destroy(tcp_taskq);
24036 }
24037 
24038 /*
24039  * Shut down the TCP stack instance.
24040  */
24041 /* ARGSUSED */
24042 static void
24043 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24044 {
24045 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24046 
24047 	tcp_g_q_destroy(tcps);
24048 }
24049 
24050 /*
24051  * Free the TCP stack instance.
24052  */
24053 static void
24054 tcp_stack_fini(netstackid_t stackid, void *arg)
24055 {
24056 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24057 	int i;
24058 
24059 	nd_free(&tcps->tcps_g_nd);
24060 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24061 	tcps->tcps_params = NULL;
24062 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24063 	tcps->tcps_wroff_xtra_param = NULL;
24064 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24065 	tcps->tcps_mdt_head_param = NULL;
24066 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24067 	tcps->tcps_mdt_tail_param = NULL;
24068 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24069 	tcps->tcps_mdt_max_pbufs_param = NULL;
24070 
24071 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24072 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24073 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24074 	}
24075 
24076 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24077 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24078 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24079 	}
24080 
24081 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24082 	tcps->tcps_bind_fanout = NULL;
24083 
24084 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24085 	tcps->tcps_acceptor_fanout = NULL;
24086 
24087 	mutex_destroy(&tcps->tcps_iss_key_lock);
24088 	mutex_destroy(&tcps->tcps_g_q_lock);
24089 	cv_destroy(&tcps->tcps_g_q_cv);
24090 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24091 
24092 	ip_drop_unregister(&tcps->tcps_dropper);
24093 
24094 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24095 	tcps->tcps_kstat = NULL;
24096 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24097 
24098 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24099 	tcps->tcps_mibkp = NULL;
24100 
24101 	ldi_ident_release(tcps->tcps_ldi_ident);
24102 	kmem_free(tcps, sizeof (*tcps));
24103 }
24104 
24105 /*
24106  * Generate ISS, taking into account NDD changes may happen halfway through.
24107  * (If the iss is not zero, set it.)
24108  */
24109 
24110 static void
24111 tcp_iss_init(tcp_t *tcp)
24112 {
24113 	MD5_CTX context;
24114 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24115 	uint32_t answer[4];
24116 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24117 
24118 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
24119 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
24120 	switch (tcps->tcps_strong_iss) {
24121 	case 2:
24122 		mutex_enter(&tcps->tcps_iss_key_lock);
24123 		context = tcps->tcps_iss_key;
24124 		mutex_exit(&tcps->tcps_iss_key_lock);
24125 		arg.ports = tcp->tcp_ports;
24126 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24127 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24128 			    &arg.src);
24129 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24130 			    &arg.dst);
24131 		} else {
24132 			arg.src = tcp->tcp_ip6h->ip6_src;
24133 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24134 		}
24135 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24136 		MD5Final((uchar_t *)answer, &context);
24137 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24138 		/*
24139 		 * Now that we've hashed into a unique per-connection sequence
24140 		 * space, add a random increment per strong_iss == 1.  So I
24141 		 * guess we'll have to...
24142 		 */
24143 		/* FALLTHRU */
24144 	case 1:
24145 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24146 		break;
24147 	default:
24148 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24149 		break;
24150 	}
24151 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24152 	tcp->tcp_fss = tcp->tcp_iss - 1;
24153 	tcp->tcp_suna = tcp->tcp_iss;
24154 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24155 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24156 	tcp->tcp_csuna = tcp->tcp_snxt;
24157 }
24158 
24159 /*
24160  * Exported routine for extracting active tcp connection status.
24161  *
24162  * This is used by the Solaris Cluster Networking software to
24163  * gather a list of connections that need to be forwarded to
24164  * specific nodes in the cluster when configuration changes occur.
24165  *
24166  * The callback is invoked for each tcp_t structure from all netstacks,
24167  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
24168  * from the netstack with the specified stack_id. Returning
24169  * non-zero from the callback routine terminates the search.
24170  */
24171 int
24172 cl_tcp_walk_list(netstackid_t stack_id,
24173     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
24174 {
24175 	netstack_handle_t nh;
24176 	netstack_t *ns;
24177 	int ret = 0;
24178 
24179 	if (stack_id >= 0) {
24180 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
24181 			return (EINVAL);
24182 
24183 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24184 		    ns->netstack_tcp);
24185 		netstack_rele(ns);
24186 		return (ret);
24187 	}
24188 
24189 	netstack_next_init(&nh);
24190 	while ((ns = netstack_next(&nh)) != NULL) {
24191 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
24192 		    ns->netstack_tcp);
24193 		netstack_rele(ns);
24194 	}
24195 	netstack_next_fini(&nh);
24196 	return (ret);
24197 }
24198 
24199 static int
24200 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
24201     tcp_stack_t *tcps)
24202 {
24203 	tcp_t *tcp;
24204 	cl_tcp_info_t	cl_tcpi;
24205 	connf_t	*connfp;
24206 	conn_t	*connp;
24207 	int	i;
24208 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24209 
24210 	ASSERT(callback != NULL);
24211 
24212 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24213 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
24214 		connp = NULL;
24215 
24216 		while ((connp =
24217 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24218 
24219 			tcp = connp->conn_tcp;
24220 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24221 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24222 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24223 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24224 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24225 			/*
24226 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24227 			 * addresses. They are copied implicitly below as
24228 			 * mapped addresses.
24229 			 */
24230 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24231 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24232 				cl_tcpi.cl_tcpi_faddr =
24233 				    tcp->tcp_ipha->ipha_dst;
24234 			} else {
24235 				cl_tcpi.cl_tcpi_faddr_v6 =
24236 				    tcp->tcp_ip6h->ip6_dst;
24237 			}
24238 
24239 			/*
24240 			 * If the callback returns non-zero
24241 			 * we terminate the traversal.
24242 			 */
24243 			if ((*callback)(&cl_tcpi, arg) != 0) {
24244 				CONN_DEC_REF(tcp->tcp_connp);
24245 				return (1);
24246 			}
24247 		}
24248 	}
24249 
24250 	return (0);
24251 }
24252 
24253 /*
24254  * Macros used for accessing the different types of sockaddr
24255  * structures inside a tcp_ioc_abort_conn_t.
24256  */
24257 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24258 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24259 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24260 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24261 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24262 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24263 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24264 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24265 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24266 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24267 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24268 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24269 
24270 /*
24271  * Return the correct error code to mimic the behavior
24272  * of a connection reset.
24273  */
24274 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24275 		switch ((state)) {		\
24276 		case TCPS_SYN_SENT:		\
24277 		case TCPS_SYN_RCVD:		\
24278 			(err) = ECONNREFUSED;	\
24279 			break;			\
24280 		case TCPS_ESTABLISHED:		\
24281 		case TCPS_FIN_WAIT_1:		\
24282 		case TCPS_FIN_WAIT_2:		\
24283 		case TCPS_CLOSE_WAIT:		\
24284 			(err) = ECONNRESET;	\
24285 			break;			\
24286 		case TCPS_CLOSING:		\
24287 		case TCPS_LAST_ACK:		\
24288 		case TCPS_TIME_WAIT:		\
24289 			(err) = 0;		\
24290 			break;			\
24291 		default:			\
24292 			(err) = ENXIO;		\
24293 		}				\
24294 	}
24295 
24296 /*
24297  * Check if a tcp structure matches the info in acp.
24298  */
24299 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24300 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24301 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24302 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24303 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24304 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24305 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24306 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24307 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24308 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24309 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24310 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24311 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24312 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24313 	&(tcp)->tcp_ip_src_v6)) &&				\
24314 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24315 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24316 	&(tcp)->tcp_remote_v6)) &&				\
24317 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24318 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24319 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24320 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24321 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24322 	(acp)->ac_end >= (tcp)->tcp_state))
24323 
24324 #define	TCP_AC_MATCH(acp, tcp)					\
24325 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24326 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24327 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24328 
24329 /*
24330  * Build a message containing a tcp_ioc_abort_conn_t structure
24331  * which is filled in with information from acp and tp.
24332  */
24333 static mblk_t *
24334 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24335 {
24336 	mblk_t *mp;
24337 	tcp_ioc_abort_conn_t *tacp;
24338 
24339 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24340 	if (mp == NULL)
24341 		return (NULL);
24342 
24343 	mp->b_datap->db_type = M_CTL;
24344 
24345 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24346 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24347 	    sizeof (uint32_t));
24348 
24349 	tacp->ac_start = acp->ac_start;
24350 	tacp->ac_end = acp->ac_end;
24351 	tacp->ac_zoneid = acp->ac_zoneid;
24352 
24353 	if (acp->ac_local.ss_family == AF_INET) {
24354 		tacp->ac_local.ss_family = AF_INET;
24355 		tacp->ac_remote.ss_family = AF_INET;
24356 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24357 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24358 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24359 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24360 	} else {
24361 		tacp->ac_local.ss_family = AF_INET6;
24362 		tacp->ac_remote.ss_family = AF_INET6;
24363 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24364 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24365 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24366 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24367 	}
24368 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24369 	return (mp);
24370 }
24371 
24372 /*
24373  * Print a tcp_ioc_abort_conn_t structure.
24374  */
24375 static void
24376 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24377 {
24378 	char lbuf[128];
24379 	char rbuf[128];
24380 	sa_family_t af;
24381 	in_port_t lport, rport;
24382 	ushort_t logflags;
24383 
24384 	af = acp->ac_local.ss_family;
24385 
24386 	if (af == AF_INET) {
24387 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24388 		    lbuf, 128);
24389 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24390 		    rbuf, 128);
24391 		lport = ntohs(TCP_AC_V4LPORT(acp));
24392 		rport = ntohs(TCP_AC_V4RPORT(acp));
24393 	} else {
24394 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24395 		    lbuf, 128);
24396 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24397 		    rbuf, 128);
24398 		lport = ntohs(TCP_AC_V6LPORT(acp));
24399 		rport = ntohs(TCP_AC_V6RPORT(acp));
24400 	}
24401 
24402 	logflags = SL_TRACE | SL_NOTE;
24403 	/*
24404 	 * Don't print this message to the console if the operation was done
24405 	 * to a non-global zone.
24406 	 */
24407 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24408 		logflags |= SL_CONSOLE;
24409 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24410 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24411 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24412 	    acp->ac_start, acp->ac_end);
24413 }
24414 
24415 /*
24416  * Called inside tcp_rput when a message built using
24417  * tcp_ioctl_abort_build_msg is put into a queue.
24418  * Note that when we get here there is no wildcard in acp any more.
24419  */
24420 static void
24421 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24422 {
24423 	tcp_ioc_abort_conn_t *acp;
24424 
24425 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24426 	if (tcp->tcp_state <= acp->ac_end) {
24427 		/*
24428 		 * If we get here, we are already on the correct
24429 		 * squeue. This ioctl follows the following path
24430 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24431 		 * ->tcp_ioctl_abort->squeue_enter (if on a
24432 		 * different squeue)
24433 		 */
24434 		int errcode;
24435 
24436 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24437 		(void) tcp_clean_death(tcp, errcode, 26);
24438 	}
24439 	freemsg(mp);
24440 }
24441 
24442 /*
24443  * Abort all matching connections on a hash chain.
24444  */
24445 static int
24446 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24447     boolean_t exact, tcp_stack_t *tcps)
24448 {
24449 	int nmatch, err = 0;
24450 	tcp_t *tcp;
24451 	MBLKP mp, last, listhead = NULL;
24452 	conn_t	*tconnp;
24453 	connf_t	*connfp;
24454 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24455 
24456 	connfp = &ipst->ips_ipcl_conn_fanout[index];
24457 
24458 startover:
24459 	nmatch = 0;
24460 
24461 	mutex_enter(&connfp->connf_lock);
24462 	for (tconnp = connfp->connf_head; tconnp != NULL;
24463 	    tconnp = tconnp->conn_next) {
24464 		tcp = tconnp->conn_tcp;
24465 		if (TCP_AC_MATCH(acp, tcp)) {
24466 			CONN_INC_REF(tcp->tcp_connp);
24467 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24468 			if (mp == NULL) {
24469 				err = ENOMEM;
24470 				CONN_DEC_REF(tcp->tcp_connp);
24471 				break;
24472 			}
24473 			mp->b_prev = (mblk_t *)tcp;
24474 
24475 			if (listhead == NULL) {
24476 				listhead = mp;
24477 				last = mp;
24478 			} else {
24479 				last->b_next = mp;
24480 				last = mp;
24481 			}
24482 			nmatch++;
24483 			if (exact)
24484 				break;
24485 		}
24486 
24487 		/* Avoid holding lock for too long. */
24488 		if (nmatch >= 500)
24489 			break;
24490 	}
24491 	mutex_exit(&connfp->connf_lock);
24492 
24493 	/* Pass mp into the correct tcp */
24494 	while ((mp = listhead) != NULL) {
24495 		listhead = listhead->b_next;
24496 		tcp = (tcp_t *)mp->b_prev;
24497 		mp->b_next = mp->b_prev = NULL;
24498 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
24499 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
24500 	}
24501 
24502 	*count += nmatch;
24503 	if (nmatch >= 500 && err == 0)
24504 		goto startover;
24505 	return (err);
24506 }
24507 
24508 /*
24509  * Abort all connections that matches the attributes specified in acp.
24510  */
24511 static int
24512 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
24513 {
24514 	sa_family_t af;
24515 	uint32_t  ports;
24516 	uint16_t *pports;
24517 	int err = 0, count = 0;
24518 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24519 	int index = -1;
24520 	ushort_t logflags;
24521 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
24522 
24523 	af = acp->ac_local.ss_family;
24524 
24525 	if (af == AF_INET) {
24526 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24527 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24528 			pports = (uint16_t *)&ports;
24529 			pports[1] = TCP_AC_V4LPORT(acp);
24530 			pports[0] = TCP_AC_V4RPORT(acp);
24531 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24532 		}
24533 	} else {
24534 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24535 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24536 			pports = (uint16_t *)&ports;
24537 			pports[1] = TCP_AC_V6LPORT(acp);
24538 			pports[0] = TCP_AC_V6RPORT(acp);
24539 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24540 		}
24541 	}
24542 
24543 	/*
24544 	 * For cases where remote addr, local port, and remote port are non-
24545 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24546 	 */
24547 	if (index != -1) {
24548 		err = tcp_ioctl_abort_bucket(acp, index,
24549 		    &count, exact, tcps);
24550 	} else {
24551 		/*
24552 		 * loop through all entries for wildcard case
24553 		 */
24554 		for (index = 0;
24555 		    index < ipst->ips_ipcl_conn_fanout_size;
24556 		    index++) {
24557 			err = tcp_ioctl_abort_bucket(acp, index,
24558 			    &count, exact, tcps);
24559 			if (err != 0)
24560 				break;
24561 		}
24562 	}
24563 
24564 	logflags = SL_TRACE | SL_NOTE;
24565 	/*
24566 	 * Don't print this message to the console if the operation was done
24567 	 * to a non-global zone.
24568 	 */
24569 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24570 		logflags |= SL_CONSOLE;
24571 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24572 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24573 	if (err == 0 && count == 0)
24574 		err = ENOENT;
24575 	return (err);
24576 }
24577 
24578 /*
24579  * Process the TCP_IOC_ABORT_CONN ioctl request.
24580  */
24581 static void
24582 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24583 {
24584 	int	err;
24585 	IOCP    iocp;
24586 	MBLKP   mp1;
24587 	sa_family_t laf, raf;
24588 	tcp_ioc_abort_conn_t *acp;
24589 	zone_t		*zptr;
24590 	conn_t		*connp = Q_TO_CONN(q);
24591 	zoneid_t	zoneid = connp->conn_zoneid;
24592 	tcp_t		*tcp = connp->conn_tcp;
24593 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24594 
24595 	iocp = (IOCP)mp->b_rptr;
24596 
24597 	if ((mp1 = mp->b_cont) == NULL ||
24598 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24599 		err = EINVAL;
24600 		goto out;
24601 	}
24602 
24603 	/* check permissions */
24604 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
24605 		err = EPERM;
24606 		goto out;
24607 	}
24608 
24609 	if (mp1->b_cont != NULL) {
24610 		freemsg(mp1->b_cont);
24611 		mp1->b_cont = NULL;
24612 	}
24613 
24614 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24615 	laf = acp->ac_local.ss_family;
24616 	raf = acp->ac_remote.ss_family;
24617 
24618 	/* check that a zone with the supplied zoneid exists */
24619 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24620 		zptr = zone_find_by_id(zoneid);
24621 		if (zptr != NULL) {
24622 			zone_rele(zptr);
24623 		} else {
24624 			err = EINVAL;
24625 			goto out;
24626 		}
24627 	}
24628 
24629 	/*
24630 	 * For exclusive stacks we set the zoneid to zero
24631 	 * to make TCP operate as if in the global zone.
24632 	 */
24633 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
24634 		acp->ac_zoneid = GLOBAL_ZONEID;
24635 
24636 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24637 	    acp->ac_start > acp->ac_end || laf != raf ||
24638 	    (laf != AF_INET && laf != AF_INET6)) {
24639 		err = EINVAL;
24640 		goto out;
24641 	}
24642 
24643 	tcp_ioctl_abort_dump(acp);
24644 	err = tcp_ioctl_abort(acp, tcps);
24645 
24646 out:
24647 	if (mp1 != NULL) {
24648 		freemsg(mp1);
24649 		mp->b_cont = NULL;
24650 	}
24651 
24652 	if (err != 0)
24653 		miocnak(q, mp, 0, err);
24654 	else
24655 		miocack(q, mp, 0, 0);
24656 }
24657 
24658 /*
24659  * tcp_time_wait_processing() handles processing of incoming packets when
24660  * the tcp is in the TIME_WAIT state.
24661  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24662  * on the time wait list.
24663  */
24664 void
24665 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24666     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24667 {
24668 	int32_t		bytes_acked;
24669 	int32_t		gap;
24670 	int32_t		rgap;
24671 	tcp_opt_t	tcpopt;
24672 	uint_t		flags;
24673 	uint32_t	new_swnd = 0;
24674 	conn_t		*connp;
24675 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24676 
24677 	BUMP_LOCAL(tcp->tcp_ibsegs);
24678 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
24679 
24680 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24681 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24682 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24683 	if (tcp->tcp_snd_ts_ok) {
24684 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24685 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24686 			    tcp->tcp_rnxt, TH_ACK);
24687 			goto done;
24688 		}
24689 	}
24690 	gap = seg_seq - tcp->tcp_rnxt;
24691 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24692 	if (gap < 0) {
24693 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
24694 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
24695 		    (seg_len > -gap ? -gap : seg_len));
24696 		seg_len += gap;
24697 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24698 			if (flags & TH_RST) {
24699 				goto done;
24700 			}
24701 			if ((flags & TH_FIN) && seg_len == -1) {
24702 				/*
24703 				 * When TCP receives a duplicate FIN in
24704 				 * TIME_WAIT state, restart the 2 MSL timer.
24705 				 * See page 73 in RFC 793. Make sure this TCP
24706 				 * is already on the TIME_WAIT list. If not,
24707 				 * just restart the timer.
24708 				 */
24709 				if (TCP_IS_DETACHED(tcp)) {
24710 					if (tcp_time_wait_remove(tcp, NULL) ==
24711 					    B_TRUE) {
24712 						tcp_time_wait_append(tcp);
24713 						TCP_DBGSTAT(tcps,
24714 						    tcp_rput_time_wait);
24715 					}
24716 				} else {
24717 					ASSERT(tcp != NULL);
24718 					TCP_TIMER_RESTART(tcp,
24719 					    tcps->tcps_time_wait_interval);
24720 				}
24721 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24722 				    tcp->tcp_rnxt, TH_ACK);
24723 				goto done;
24724 			}
24725 			flags |=  TH_ACK_NEEDED;
24726 			seg_len = 0;
24727 			goto process_ack;
24728 		}
24729 
24730 		/* Fix seg_seq, and chew the gap off the front. */
24731 		seg_seq = tcp->tcp_rnxt;
24732 	}
24733 
24734 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24735 		/*
24736 		 * Make sure that when we accept the connection, pick
24737 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24738 		 * old connection.
24739 		 *
24740 		 * The next ISS generated is equal to tcp_iss_incr_extra
24741 		 * + ISS_INCR/2 + other components depending on the
24742 		 * value of tcp_strong_iss.  We pre-calculate the new
24743 		 * ISS here and compare with tcp_snxt to determine if
24744 		 * we need to make adjustment to tcp_iss_incr_extra.
24745 		 *
24746 		 * The above calculation is ugly and is a
24747 		 * waste of CPU cycles...
24748 		 */
24749 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
24750 		int32_t adj;
24751 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
24752 
24753 		switch (tcps->tcps_strong_iss) {
24754 		case 2: {
24755 			/* Add time and MD5 components. */
24756 			uint32_t answer[4];
24757 			struct {
24758 				uint32_t ports;
24759 				in6_addr_t src;
24760 				in6_addr_t dst;
24761 			} arg;
24762 			MD5_CTX context;
24763 
24764 			mutex_enter(&tcps->tcps_iss_key_lock);
24765 			context = tcps->tcps_iss_key;
24766 			mutex_exit(&tcps->tcps_iss_key_lock);
24767 			arg.ports = tcp->tcp_ports;
24768 			/* We use MAPPED addresses in tcp_iss_init */
24769 			arg.src = tcp->tcp_ip_src_v6;
24770 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24771 				IN6_IPADDR_TO_V4MAPPED(
24772 				    tcp->tcp_ipha->ipha_dst,
24773 				    &arg.dst);
24774 			} else {
24775 				arg.dst =
24776 				    tcp->tcp_ip6h->ip6_dst;
24777 			}
24778 			MD5Update(&context, (uchar_t *)&arg,
24779 			    sizeof (arg));
24780 			MD5Final((uchar_t *)answer, &context);
24781 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24782 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24783 			break;
24784 		}
24785 		case 1:
24786 			/* Add time component and min random (i.e. 1). */
24787 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24788 			break;
24789 		default:
24790 			/* Add only time component. */
24791 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24792 			break;
24793 		}
24794 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24795 			/*
24796 			 * New ISS not guaranteed to be ISS_INCR/2
24797 			 * ahead of the current tcp_snxt, so add the
24798 			 * difference to tcp_iss_incr_extra.
24799 			 */
24800 			tcps->tcps_iss_incr_extra += adj;
24801 		}
24802 		/*
24803 		 * If tcp_clean_death() can not perform the task now,
24804 		 * drop the SYN packet and let the other side re-xmit.
24805 		 * Otherwise pass the SYN packet back in, since the
24806 		 * old tcp state has been cleaned up or freed.
24807 		 */
24808 		if (tcp_clean_death(tcp, 0, 27) == -1)
24809 			goto done;
24810 		/*
24811 		 * We will come back to tcp_rput_data
24812 		 * on the global queue. Packets destined
24813 		 * for the global queue will be checked
24814 		 * with global policy. But the policy for
24815 		 * this packet has already been checked as
24816 		 * this was destined for the detached
24817 		 * connection. We need to bypass policy
24818 		 * check this time by attaching a dummy
24819 		 * ipsec_in with ipsec_in_dont_check set.
24820 		 */
24821 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
24822 		if (connp != NULL) {
24823 			TCP_STAT(tcps, tcp_time_wait_syn_success);
24824 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24825 			return;
24826 		}
24827 		goto done;
24828 	}
24829 
24830 	/*
24831 	 * rgap is the amount of stuff received out of window.  A negative
24832 	 * value is the amount out of window.
24833 	 */
24834 	if (rgap < 0) {
24835 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
24836 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
24837 		/* Fix seg_len and make sure there is something left. */
24838 		seg_len += rgap;
24839 		if (seg_len <= 0) {
24840 			if (flags & TH_RST) {
24841 				goto done;
24842 			}
24843 			flags |=  TH_ACK_NEEDED;
24844 			seg_len = 0;
24845 			goto process_ack;
24846 		}
24847 	}
24848 	/*
24849 	 * Check whether we can update tcp_ts_recent.  This test is
24850 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24851 	 * Extensions for High Performance: An Update", Internet Draft.
24852 	 */
24853 	if (tcp->tcp_snd_ts_ok &&
24854 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24855 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24856 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24857 		tcp->tcp_last_rcv_lbolt = lbolt64;
24858 	}
24859 
24860 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24861 		/* Always ack out of order packets */
24862 		flags |= TH_ACK_NEEDED;
24863 		seg_len = 0;
24864 	} else if (seg_len > 0) {
24865 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
24866 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
24867 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
24868 	}
24869 	if (flags & TH_RST) {
24870 		(void) tcp_clean_death(tcp, 0, 28);
24871 		goto done;
24872 	}
24873 	if (flags & TH_SYN) {
24874 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24875 		    TH_RST|TH_ACK);
24876 		/*
24877 		 * Do not delete the TCP structure if it is in
24878 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24879 		 */
24880 		goto done;
24881 	}
24882 process_ack:
24883 	if (flags & TH_ACK) {
24884 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24885 		if (bytes_acked <= 0) {
24886 			if (bytes_acked == 0 && seg_len == 0 &&
24887 			    new_swnd == tcp->tcp_swnd)
24888 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
24889 		} else {
24890 			/* Acks something not sent */
24891 			flags |= TH_ACK_NEEDED;
24892 		}
24893 	}
24894 	if (flags & TH_ACK_NEEDED) {
24895 		/*
24896 		 * Time to send an ack for some reason.
24897 		 */
24898 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24899 		    tcp->tcp_rnxt, TH_ACK);
24900 	}
24901 done:
24902 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24903 		DB_CKSUMSTART(mp) = 0;
24904 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24905 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
24906 	}
24907 	freemsg(mp);
24908 }
24909 
24910 /*
24911  * TCP Timers Implementation.
24912  */
24913 timeout_id_t
24914 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24915 {
24916 	mblk_t *mp;
24917 	tcp_timer_t *tcpt;
24918 	tcp_t *tcp = connp->conn_tcp;
24919 
24920 	ASSERT(connp->conn_sqp != NULL);
24921 
24922 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
24923 
24924 	if (tcp->tcp_timercache == NULL) {
24925 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24926 	} else {
24927 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
24928 		mp = tcp->tcp_timercache;
24929 		tcp->tcp_timercache = mp->b_next;
24930 		mp->b_next = NULL;
24931 		ASSERT(mp->b_wptr == NULL);
24932 	}
24933 
24934 	CONN_INC_REF(connp);
24935 	tcpt = (tcp_timer_t *)mp->b_rptr;
24936 	tcpt->connp = connp;
24937 	tcpt->tcpt_proc = f;
24938 	/*
24939 	 * TCP timers are normal timeouts. Plus, they do not require more than
24940 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
24941 	 * rounding up the expiration to the next resolution boundary, we can
24942 	 * batch timers in the callout subsystem to make TCP timers more
24943 	 * efficient. The roundup also protects short timers from expiring too
24944 	 * early before they have a chance to be cancelled.
24945 	 */
24946 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
24947 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
24948 
24949 	return ((timeout_id_t)mp);
24950 }
24951 
24952 static void
24953 tcp_timer_callback(void *arg)
24954 {
24955 	mblk_t *mp = (mblk_t *)arg;
24956 	tcp_timer_t *tcpt;
24957 	conn_t	*connp;
24958 
24959 	tcpt = (tcp_timer_t *)mp->b_rptr;
24960 	connp = tcpt->connp;
24961 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
24962 	    SQ_FILL, SQTAG_TCP_TIMER);
24963 }
24964 
24965 static void
24966 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24967 {
24968 	tcp_timer_t *tcpt;
24969 	conn_t *connp = (conn_t *)arg;
24970 	tcp_t *tcp = connp->conn_tcp;
24971 
24972 	tcpt = (tcp_timer_t *)mp->b_rptr;
24973 	ASSERT(connp == tcpt->connp);
24974 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24975 
24976 	/*
24977 	 * If the TCP has reached the closed state, don't proceed any
24978 	 * further. This TCP logically does not exist on the system.
24979 	 * tcpt_proc could for example access queues, that have already
24980 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24981 	 */
24982 	if (tcp->tcp_state != TCPS_CLOSED) {
24983 		(*tcpt->tcpt_proc)(connp);
24984 	} else {
24985 		tcp->tcp_timer_tid = 0;
24986 	}
24987 	tcp_timer_free(connp->conn_tcp, mp);
24988 }
24989 
24990 /*
24991  * There is potential race with untimeout and the handler firing at the same
24992  * time. The mblock may be freed by the handler while we are trying to use
24993  * it. But since both should execute on the same squeue, this race should not
24994  * occur.
24995  */
24996 clock_t
24997 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24998 {
24999 	mblk_t	*mp = (mblk_t *)id;
25000 	tcp_timer_t *tcpt;
25001 	clock_t delta;
25002 
25003 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25004 
25005 	if (mp == NULL)
25006 		return (-1);
25007 
25008 	tcpt = (tcp_timer_t *)mp->b_rptr;
25009 	ASSERT(tcpt->connp == connp);
25010 
25011 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25012 
25013 	if (delta >= 0) {
25014 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
25015 		tcp_timer_free(connp->conn_tcp, mp);
25016 		CONN_DEC_REF(connp);
25017 	}
25018 
25019 	return (delta);
25020 }
25021 
25022 /*
25023  * Allocate space for the timer event. The allocation looks like mblk, but it is
25024  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25025  *
25026  * Dealing with failures: If we can't allocate from the timer cache we try
25027  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25028  * points to b_rptr.
25029  * If we can't allocate anything using allocb_tryhard(), we perform a last
25030  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25031  * save the actual allocation size in b_datap.
25032  */
25033 mblk_t *
25034 tcp_timermp_alloc(int kmflags)
25035 {
25036 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25037 	    kmflags & ~KM_PANIC);
25038 
25039 	if (mp != NULL) {
25040 		mp->b_next = mp->b_prev = NULL;
25041 		mp->b_rptr = (uchar_t *)(&mp[1]);
25042 		mp->b_wptr = NULL;
25043 		mp->b_datap = NULL;
25044 		mp->b_queue = NULL;
25045 		mp->b_cont = NULL;
25046 	} else if (kmflags & KM_PANIC) {
25047 		/*
25048 		 * Failed to allocate memory for the timer. Try allocating from
25049 		 * dblock caches.
25050 		 */
25051 		/* ipclassifier calls this from a constructor - hence no tcps */
25052 		TCP_G_STAT(tcp_timermp_allocfail);
25053 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25054 		if (mp == NULL) {
25055 			size_t size = 0;
25056 			/*
25057 			 * Memory is really low. Try tryhard allocation.
25058 			 *
25059 			 * ipclassifier calls this from a constructor -
25060 			 * hence no tcps
25061 			 */
25062 			TCP_G_STAT(tcp_timermp_allocdblfail);
25063 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25064 			    sizeof (tcp_timer_t), &size, kmflags);
25065 			mp->b_rptr = (uchar_t *)(&mp[1]);
25066 			mp->b_next = mp->b_prev = NULL;
25067 			mp->b_wptr = (uchar_t *)-1;
25068 			mp->b_datap = (dblk_t *)size;
25069 			mp->b_queue = NULL;
25070 			mp->b_cont = NULL;
25071 		}
25072 		ASSERT(mp->b_wptr != NULL);
25073 	}
25074 	/* ipclassifier calls this from a constructor - hence no tcps */
25075 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25076 
25077 	return (mp);
25078 }
25079 
25080 /*
25081  * Free per-tcp timer cache.
25082  * It can only contain entries from tcp_timercache.
25083  */
25084 void
25085 tcp_timermp_free(tcp_t *tcp)
25086 {
25087 	mblk_t *mp;
25088 
25089 	while ((mp = tcp->tcp_timercache) != NULL) {
25090 		ASSERT(mp->b_wptr == NULL);
25091 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25092 		kmem_cache_free(tcp_timercache, mp);
25093 	}
25094 }
25095 
25096 /*
25097  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25098  * events there already (currently at most two events are cached).
25099  * If the event is not allocated from the timer cache, free it right away.
25100  */
25101 static void
25102 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25103 {
25104 	mblk_t *mp1 = tcp->tcp_timercache;
25105 
25106 	if (mp->b_wptr != NULL) {
25107 		/*
25108 		 * This allocation is not from a timer cache, free it right
25109 		 * away.
25110 		 */
25111 		if (mp->b_wptr != (uchar_t *)-1)
25112 			freeb(mp);
25113 		else
25114 			kmem_free(mp, (size_t)mp->b_datap);
25115 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25116 		/* Cache this timer block for future allocations */
25117 		mp->b_rptr = (uchar_t *)(&mp[1]);
25118 		mp->b_next = mp1;
25119 		tcp->tcp_timercache = mp;
25120 	} else {
25121 		kmem_cache_free(tcp_timercache, mp);
25122 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
25123 	}
25124 }
25125 
25126 /*
25127  * End of TCP Timers implementation.
25128  */
25129 
25130 /*
25131  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25132  * on the specified backing STREAMS q. Note, the caller may make the
25133  * decision to call based on the tcp_t.tcp_flow_stopped value which
25134  * when check outside the q's lock is only an advisory check ...
25135  */
25136 void
25137 tcp_setqfull(tcp_t *tcp)
25138 {
25139 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25140 	conn_t	*connp = tcp->tcp_connp;
25141 
25142 	if (tcp->tcp_closed)
25143 		return;
25144 
25145 	if (IPCL_IS_NONSTR(connp)) {
25146 		(*connp->conn_upcalls->su_txq_full)
25147 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
25148 		tcp->tcp_flow_stopped = B_TRUE;
25149 	} else {
25150 		queue_t *q = tcp->tcp_wq;
25151 
25152 		if (!(q->q_flag & QFULL)) {
25153 			mutex_enter(QLOCK(q));
25154 			if (!(q->q_flag & QFULL)) {
25155 				/* still need to set QFULL */
25156 				q->q_flag |= QFULL;
25157 				tcp->tcp_flow_stopped = B_TRUE;
25158 				mutex_exit(QLOCK(q));
25159 				TCP_STAT(tcps, tcp_flwctl_on);
25160 			} else {
25161 				mutex_exit(QLOCK(q));
25162 			}
25163 		}
25164 	}
25165 }
25166 
25167 void
25168 tcp_clrqfull(tcp_t *tcp)
25169 {
25170 	conn_t  *connp = tcp->tcp_connp;
25171 
25172 	if (tcp->tcp_closed)
25173 		return;
25174 
25175 	if (IPCL_IS_NONSTR(connp)) {
25176 		(*connp->conn_upcalls->su_txq_full)
25177 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
25178 		tcp->tcp_flow_stopped = B_FALSE;
25179 	} else {
25180 		queue_t *q = tcp->tcp_wq;
25181 
25182 		if (q->q_flag & QFULL) {
25183 			mutex_enter(QLOCK(q));
25184 			if (q->q_flag & QFULL) {
25185 				q->q_flag &= ~QFULL;
25186 				tcp->tcp_flow_stopped = B_FALSE;
25187 				mutex_exit(QLOCK(q));
25188 				if (q->q_flag & QWANTW)
25189 					qbackenable(q, 0);
25190 			} else {
25191 				mutex_exit(QLOCK(q));
25192 			}
25193 		}
25194 	}
25195 }
25196 
25197 /*
25198  * kstats related to squeues i.e. not per IP instance
25199  */
25200 static void *
25201 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
25202 {
25203 	kstat_t *ksp;
25204 
25205 	tcp_g_stat_t template = {
25206 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
25207 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
25208 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
25209 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
25210 	};
25211 
25212 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
25213 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25214 	    KSTAT_FLAG_VIRTUAL);
25215 
25216 	if (ksp == NULL)
25217 		return (NULL);
25218 
25219 	bcopy(&template, tcp_g_statp, sizeof (template));
25220 	ksp->ks_data = (void *)tcp_g_statp;
25221 
25222 	kstat_install(ksp);
25223 	return (ksp);
25224 }
25225 
25226 static void
25227 tcp_g_kstat_fini(kstat_t *ksp)
25228 {
25229 	if (ksp != NULL) {
25230 		kstat_delete(ksp);
25231 	}
25232 }
25233 
25234 
25235 static void *
25236 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
25237 {
25238 	kstat_t *ksp;
25239 
25240 	tcp_stat_t template = {
25241 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
25242 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
25243 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
25244 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
25245 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
25246 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
25247 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
25248 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
25249 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
25250 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
25251 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
25252 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
25253 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
25254 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
25255 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
25256 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
25257 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
25258 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
25259 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
25260 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
25261 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
25262 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
25263 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
25264 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
25265 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
25266 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
25267 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
25268 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
25269 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
25270 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
25271 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
25272 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
25273 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
25274 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
25275 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
25276 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
25277 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
25278 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
25279 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
25280 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
25281 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
25282 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
25283 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
25284 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
25285 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
25286 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
25287 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
25288 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
25289 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
25290 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
25291 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
25292 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
25293 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
25294 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
25295 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
25296 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
25297 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
25298 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
25299 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
25300 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
25301 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
25302 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
25303 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
25304 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
25305 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
25306 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
25307 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
25308 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
25309 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
25310 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
25311 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
25312 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
25313 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
25314 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
25315 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
25316 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
25317 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
25318 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
25319 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
25320 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
25321 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
25322 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
25323 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
25324 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
25325 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
25326 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
25327 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
25328 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
25329 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
25330 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
25331 	};
25332 
25333 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
25334 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
25335 	    KSTAT_FLAG_VIRTUAL, stackid);
25336 
25337 	if (ksp == NULL)
25338 		return (NULL);
25339 
25340 	bcopy(&template, tcps_statisticsp, sizeof (template));
25341 	ksp->ks_data = (void *)tcps_statisticsp;
25342 	ksp->ks_private = (void *)(uintptr_t)stackid;
25343 
25344 	kstat_install(ksp);
25345 	return (ksp);
25346 }
25347 
25348 static void
25349 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
25350 {
25351 	if (ksp != NULL) {
25352 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25353 		kstat_delete_netstack(ksp, stackid);
25354 	}
25355 }
25356 
25357 /*
25358  * TCP Kstats implementation
25359  */
25360 static void *
25361 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
25362 {
25363 	kstat_t	*ksp;
25364 
25365 	tcp_named_kstat_t template = {
25366 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25367 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25368 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25369 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25370 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25371 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25372 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25373 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25374 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25375 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
25376 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
25377 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25378 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25379 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25380 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25381 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25382 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25383 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25384 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25385 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25386 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25387 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25388 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25389 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25390 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25391 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25392 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25393 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25394 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25395 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25396 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25397 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25398 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25399 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25400 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25401 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25402 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25403 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25404 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25405 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25406 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25407 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25408 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25409 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25410 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25411 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25412 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25413 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25414 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25415 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25416 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25417 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25418 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25419 	};
25420 
25421 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
25422 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
25423 
25424 	if (ksp == NULL)
25425 		return (NULL);
25426 
25427 	template.rtoAlgorithm.value.ui32 = 4;
25428 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
25429 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
25430 	template.maxConn.value.i32 = -1;
25431 
25432 	bcopy(&template, ksp->ks_data, sizeof (template));
25433 	ksp->ks_update = tcp_kstat_update;
25434 	ksp->ks_private = (void *)(uintptr_t)stackid;
25435 
25436 	kstat_install(ksp);
25437 	return (ksp);
25438 }
25439 
25440 static void
25441 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
25442 {
25443 	if (ksp != NULL) {
25444 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
25445 		kstat_delete_netstack(ksp, stackid);
25446 	}
25447 }
25448 
25449 static int
25450 tcp_kstat_update(kstat_t *kp, int rw)
25451 {
25452 	tcp_named_kstat_t *tcpkp;
25453 	tcp_t		*tcp;
25454 	connf_t		*connfp;
25455 	conn_t		*connp;
25456 	int 		i;
25457 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
25458 	netstack_t	*ns;
25459 	tcp_stack_t	*tcps;
25460 	ip_stack_t	*ipst;
25461 
25462 	if ((kp == NULL) || (kp->ks_data == NULL))
25463 		return (EIO);
25464 
25465 	if (rw == KSTAT_WRITE)
25466 		return (EACCES);
25467 
25468 	ns = netstack_find_by_stackid(stackid);
25469 	if (ns == NULL)
25470 		return (-1);
25471 	tcps = ns->netstack_tcp;
25472 	if (tcps == NULL) {
25473 		netstack_rele(ns);
25474 		return (-1);
25475 	}
25476 
25477 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25478 
25479 	tcpkp->currEstab.value.ui32 = 0;
25480 
25481 	ipst = ns->netstack_ip;
25482 
25483 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25484 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25485 		connp = NULL;
25486 		while ((connp =
25487 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25488 			tcp = connp->conn_tcp;
25489 			switch (tcp_snmp_state(tcp)) {
25490 			case MIB2_TCP_established:
25491 			case MIB2_TCP_closeWait:
25492 				tcpkp->currEstab.value.ui32++;
25493 				break;
25494 			}
25495 		}
25496 	}
25497 
25498 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
25499 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
25500 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
25501 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
25502 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
25503 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
25504 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
25505 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
25506 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
25507 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
25508 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
25509 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
25510 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
25511 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
25512 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
25513 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
25514 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
25515 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
25516 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
25517 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
25518 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
25519 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
25520 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
25521 	tcpkp->inDataInorderSegs.value.ui32 =
25522 	    tcps->tcps_mib.tcpInDataInorderSegs;
25523 	tcpkp->inDataInorderBytes.value.ui32 =
25524 	    tcps->tcps_mib.tcpInDataInorderBytes;
25525 	tcpkp->inDataUnorderSegs.value.ui32 =
25526 	    tcps->tcps_mib.tcpInDataUnorderSegs;
25527 	tcpkp->inDataUnorderBytes.value.ui32 =
25528 	    tcps->tcps_mib.tcpInDataUnorderBytes;
25529 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
25530 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
25531 	tcpkp->inDataPartDupSegs.value.ui32 =
25532 	    tcps->tcps_mib.tcpInDataPartDupSegs;
25533 	tcpkp->inDataPartDupBytes.value.ui32 =
25534 	    tcps->tcps_mib.tcpInDataPartDupBytes;
25535 	tcpkp->inDataPastWinSegs.value.ui32 =
25536 	    tcps->tcps_mib.tcpInDataPastWinSegs;
25537 	tcpkp->inDataPastWinBytes.value.ui32 =
25538 	    tcps->tcps_mib.tcpInDataPastWinBytes;
25539 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
25540 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
25541 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
25542 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
25543 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
25544 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
25545 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
25546 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
25547 	tcpkp->timKeepaliveProbe.value.ui32 =
25548 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
25549 	tcpkp->timKeepaliveDrop.value.ui32 =
25550 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
25551 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
25552 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
25553 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
25554 	tcpkp->outSackRetransSegs.value.ui32 =
25555 	    tcps->tcps_mib.tcpOutSackRetransSegs;
25556 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
25557 
25558 	netstack_rele(ns);
25559 	return (0);
25560 }
25561 
25562 void
25563 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25564 {
25565 	uint16_t	hdr_len;
25566 	ipha_t		*ipha;
25567 	uint8_t		*nexthdrp;
25568 	tcph_t		*tcph;
25569 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
25570 
25571 	/* Already has an eager */
25572 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25573 		TCP_STAT(tcps, tcp_reinput_syn);
25574 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25575 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
25576 		return;
25577 	}
25578 
25579 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25580 	case IPV4_VERSION:
25581 		ipha = (ipha_t *)mp->b_rptr;
25582 		hdr_len = IPH_HDR_LENGTH(ipha);
25583 		break;
25584 	case IPV6_VERSION:
25585 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25586 		    &hdr_len, &nexthdrp)) {
25587 			CONN_DEC_REF(connp);
25588 			freemsg(mp);
25589 			return;
25590 		}
25591 		break;
25592 	}
25593 
25594 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25595 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25596 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25597 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25598 	}
25599 
25600 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
25601 	    SQ_FILL, SQTAG_TCP_REINPUT);
25602 }
25603 
25604 static int
25605 tcp_squeue_switch(int val)
25606 {
25607 	int rval = SQ_FILL;
25608 
25609 	switch (val) {
25610 	case 1:
25611 		rval = SQ_NODRAIN;
25612 		break;
25613 	case 2:
25614 		rval = SQ_PROCESS;
25615 		break;
25616 	default:
25617 		break;
25618 	}
25619 	return (rval);
25620 }
25621 
25622 /*
25623  * This is called once for each squeue - globally for all stack
25624  * instances.
25625  */
25626 static void
25627 tcp_squeue_add(squeue_t *sqp)
25628 {
25629 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25630 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
25631 
25632 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25633 	tcp_time_wait->tcp_time_wait_tid =
25634 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
25635 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
25636 	    CALLOUT_FLAG_ROUNDUP);
25637 	if (tcp_free_list_max_cnt == 0) {
25638 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25639 		    max_ncpus : boot_max_ncpus);
25640 
25641 		/*
25642 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25643 		 */
25644 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25645 		    (tcp_ncpus * sizeof (tcp_t) * 100);
25646 	}
25647 	tcp_time_wait->tcp_free_list_cnt = 0;
25648 }
25649 
25650 static int
25651 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
25652 {
25653 	mblk_t	*ire_mp = NULL;
25654 	mblk_t	*syn_mp;
25655 	mblk_t	*mdti;
25656 	mblk_t	*lsoi;
25657 	int	retval;
25658 	tcph_t	*tcph;
25659 	cred_t	*ecr;
25660 	ts_label_t	*tsl;
25661 	uint32_t	mss;
25662 	conn_t	*connp = tcp->tcp_connp;
25663 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25664 
25665 	if (error == 0) {
25666 		/*
25667 		 * Adapt Multidata information, if any.  The
25668 		 * following tcp_mdt_update routine will free
25669 		 * the message.
25670 		 */
25671 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
25672 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
25673 			    b_rptr)->mdt_capab, B_TRUE);
25674 			freemsg(mdti);
25675 		}
25676 
25677 		/*
25678 		 * Check to update LSO information with tcp, and
25679 		 * tcp_lso_update routine will free the message.
25680 		 */
25681 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
25682 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
25683 			    b_rptr)->lso_capab);
25684 			freemsg(lsoi);
25685 		}
25686 
25687 		/* Get the IRE, if we had requested for it */
25688 		if (mp != NULL)
25689 			ire_mp = tcp_ire_mp(&mp);
25690 
25691 		if (tcp->tcp_hard_binding) {
25692 			tcp->tcp_hard_binding = B_FALSE;
25693 			tcp->tcp_hard_bound = B_TRUE;
25694 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
25695 			if (retval != 0) {
25696 				error = EADDRINUSE;
25697 				goto bind_failed;
25698 			}
25699 		} else {
25700 			if (ire_mp != NULL)
25701 				freeb(ire_mp);
25702 			goto after_syn_sent;
25703 		}
25704 
25705 		retval = tcp_adapt_ire(tcp, ire_mp);
25706 		if (ire_mp != NULL)
25707 			freeb(ire_mp);
25708 		if (retval == 0) {
25709 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
25710 			    ENETUNREACH : EADDRNOTAVAIL);
25711 			goto ipcl_rm;
25712 		}
25713 		/*
25714 		 * Don't let an endpoint connect to itself.
25715 		 * Also checked in tcp_connect() but that
25716 		 * check can't handle the case when the
25717 		 * local IP address is INADDR_ANY.
25718 		 */
25719 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25720 			if ((tcp->tcp_ipha->ipha_dst ==
25721 			    tcp->tcp_ipha->ipha_src) &&
25722 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25723 			    tcp->tcp_tcph->th_fport))) {
25724 				error = EADDRNOTAVAIL;
25725 				goto ipcl_rm;
25726 			}
25727 		} else {
25728 			if (IN6_ARE_ADDR_EQUAL(
25729 			    &tcp->tcp_ip6h->ip6_dst,
25730 			    &tcp->tcp_ip6h->ip6_src) &&
25731 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
25732 			    tcp->tcp_tcph->th_fport))) {
25733 				error = EADDRNOTAVAIL;
25734 				goto ipcl_rm;
25735 			}
25736 		}
25737 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
25738 		/*
25739 		 * This should not be possible!  Just for
25740 		 * defensive coding...
25741 		 */
25742 		if (tcp->tcp_state != TCPS_SYN_SENT)
25743 			goto after_syn_sent;
25744 
25745 		if (is_system_labeled() &&
25746 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
25747 			error = EHOSTUNREACH;
25748 			goto ipcl_rm;
25749 		}
25750 
25751 		/*
25752 		 * tcp_adapt_ire() does not adjust
25753 		 * for TCP/IP header length.
25754 		 */
25755 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
25756 
25757 		/*
25758 		 * Just make sure our rwnd is at
25759 		 * least tcp_recv_hiwat_mss * MSS
25760 		 * large, and round up to the nearest
25761 		 * MSS.
25762 		 *
25763 		 * We do the round up here because
25764 		 * we need to get the interface
25765 		 * MTU first before we can do the
25766 		 * round up.
25767 		 */
25768 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
25769 		    tcps->tcps_recv_hiwat_minmss * mss);
25770 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
25771 		tcp_set_ws_value(tcp);
25772 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
25773 		    tcp->tcp_tcph->th_win);
25774 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
25775 			tcp->tcp_snd_ws_ok = B_TRUE;
25776 
25777 		/*
25778 		 * Set tcp_snd_ts_ok to true
25779 		 * so that tcp_xmit_mp will
25780 		 * include the timestamp
25781 		 * option in the SYN segment.
25782 		 */
25783 		if (tcps->tcps_tstamp_always ||
25784 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
25785 			tcp->tcp_snd_ts_ok = B_TRUE;
25786 		}
25787 
25788 		/*
25789 		 * tcp_snd_sack_ok can be set in
25790 		 * tcp_adapt_ire() if the sack metric
25791 		 * is set.  So check it here also.
25792 		 */
25793 		if (tcps->tcps_sack_permitted == 2 ||
25794 		    tcp->tcp_snd_sack_ok) {
25795 			if (tcp->tcp_sack_info == NULL) {
25796 				tcp->tcp_sack_info =
25797 				    kmem_cache_alloc(tcp_sack_info_cache,
25798 				    KM_SLEEP);
25799 			}
25800 			tcp->tcp_snd_sack_ok = B_TRUE;
25801 		}
25802 
25803 		/*
25804 		 * Should we use ECN?  Note that the current
25805 		 * default value (SunOS 5.9) of tcp_ecn_permitted
25806 		 * is 1.  The reason for doing this is that there
25807 		 * are equipments out there that will drop ECN
25808 		 * enabled IP packets.  Setting it to 1 avoids
25809 		 * compatibility problems.
25810 		 */
25811 		if (tcps->tcps_ecn_permitted == 2)
25812 			tcp->tcp_ecn_ok = B_TRUE;
25813 
25814 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
25815 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
25816 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
25817 		if (syn_mp) {
25818 			/*
25819 			 * cr contains the cred from the thread calling
25820 			 * connect().
25821 			 *
25822 			 * If no thread cred is available, use the
25823 			 * socket creator's cred instead. If still no
25824 			 * cred, drop the request rather than risk a
25825 			 * panic on production systems.
25826 			 */
25827 			if (cr == NULL) {
25828 				cr = CONN_CRED(connp);
25829 				pid = tcp->tcp_cpid;
25830 				ASSERT(cr != NULL);
25831 				if (cr != NULL) {
25832 					mblk_setcred(syn_mp, cr, pid);
25833 				} else {
25834 					error = ECONNABORTED;
25835 					goto ipcl_rm;
25836 				}
25837 
25838 			/*
25839 			 * If an effective security label exists for
25840 			 * the connection, create a copy of the thread's
25841 			 * cred but with the effective label attached.
25842 			 */
25843 			} else if (is_system_labeled() &&
25844 			    connp->conn_effective_cred != NULL &&
25845 			    (tsl = crgetlabel(connp->
25846 			    conn_effective_cred)) != NULL) {
25847 				if ((ecr = copycred_from_tslabel(cr,
25848 				    tsl, KM_NOSLEEP)) == NULL) {
25849 					error = ENOMEM;
25850 					goto ipcl_rm;
25851 				}
25852 				mblk_setcred(syn_mp, ecr, pid);
25853 				crfree(ecr);
25854 
25855 			/*
25856 			 * Default to using the thread's cred unchanged.
25857 			 */
25858 			} else {
25859 				mblk_setcred(syn_mp, cr, pid);
25860 			}
25861 
25862 			/*
25863 			 * We must bump the generation before sending the syn
25864 			 * to ensure that we use the right generation in case
25865 			 * this thread issues a "connected" up call.
25866 			 */
25867 			SOCK_CONNID_BUMP(tcp->tcp_connid);
25868 
25869 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
25870 		}
25871 	after_syn_sent:
25872 		if (mp != NULL) {
25873 			ASSERT(mp->b_cont == NULL);
25874 			freeb(mp);
25875 		}
25876 		return (error);
25877 	} else {
25878 		/* error */
25879 		if (tcp->tcp_debug) {
25880 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
25881 			    "tcp_post_ip_bind: error == %d", error);
25882 		}
25883 		if (mp != NULL) {
25884 			freeb(mp);
25885 		}
25886 	}
25887 
25888 ipcl_rm:
25889 	/*
25890 	 * Need to unbind with classifier since we were just
25891 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
25892 	 */
25893 	tcp->tcp_hard_bound = B_FALSE;
25894 	tcp->tcp_hard_binding = B_FALSE;
25895 
25896 	ipcl_hash_remove(connp);
25897 
25898 bind_failed:
25899 	tcp->tcp_state = TCPS_IDLE;
25900 	if (tcp->tcp_ipversion == IPV4_VERSION)
25901 		tcp->tcp_ipha->ipha_src = 0;
25902 	else
25903 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
25904 	/*
25905 	 * Copy of the src addr. in tcp_t is needed since
25906 	 * the lookup funcs. can only look at tcp_t
25907 	 */
25908 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
25909 
25910 	tcph = tcp->tcp_tcph;
25911 	tcph->th_lport[0] = 0;
25912 	tcph->th_lport[1] = 0;
25913 	tcp_bind_hash_remove(tcp);
25914 	bzero(&connp->u_port, sizeof (connp->u_port));
25915 	/* blow away saved option results if any */
25916 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
25917 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
25918 
25919 	conn_delete_ire(tcp->tcp_connp, NULL);
25920 
25921 	return (error);
25922 }
25923 
25924 static int
25925 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
25926     boolean_t bind_to_req_port_only, cred_t *cr)
25927 {
25928 	in_port_t	mlp_port;
25929 	mlp_type_t 	addrtype, mlptype;
25930 	boolean_t	user_specified;
25931 	in_port_t	allocated_port;
25932 	in_port_t	requested_port = *requested_port_ptr;
25933 	conn_t		*connp;
25934 	zone_t		*zone;
25935 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25936 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
25937 
25938 	/*
25939 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
25940 	 */
25941 	if (cr == NULL)
25942 		cr = tcp->tcp_cred;
25943 	/*
25944 	 * Get a valid port (within the anonymous range and should not
25945 	 * be a privileged one) to use if the user has not given a port.
25946 	 * If multiple threads are here, they may all start with
25947 	 * with the same initial port. But, it should be fine as long as
25948 	 * tcp_bindi will ensure that no two threads will be assigned
25949 	 * the same port.
25950 	 *
25951 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
25952 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
25953 	 * unless TCP_ANONPRIVBIND option is set.
25954 	 */
25955 	mlptype = mlptSingle;
25956 	mlp_port = requested_port;
25957 	if (requested_port == 0) {
25958 		requested_port = tcp->tcp_anon_priv_bind ?
25959 		    tcp_get_next_priv_port(tcp) :
25960 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
25961 		    tcp, B_TRUE);
25962 		if (requested_port == 0) {
25963 			return (-TNOADDR);
25964 		}
25965 		user_specified = B_FALSE;
25966 
25967 		/*
25968 		 * If the user went through one of the RPC interfaces to create
25969 		 * this socket and RPC is MLP in this zone, then give him an
25970 		 * anonymous MLP.
25971 		 */
25972 		connp = tcp->tcp_connp;
25973 		if (connp->conn_anon_mlp && is_system_labeled()) {
25974 			zone = crgetzone(cr);
25975 			addrtype = tsol_mlp_addr_type(
25976 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
25977 			    IPV6_VERSION, &v6addr,
25978 			    tcps->tcps_netstack->netstack_ip);
25979 			if (addrtype == mlptSingle) {
25980 				return (-TNOADDR);
25981 			}
25982 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
25983 			    PMAPPORT, addrtype);
25984 			mlp_port = PMAPPORT;
25985 		}
25986 	} else {
25987 		int i;
25988 		boolean_t priv = B_FALSE;
25989 
25990 		/*
25991 		 * If the requested_port is in the well-known privileged range,
25992 		 * verify that the stream was opened by a privileged user.
25993 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
25994 		 * but instead the code relies on:
25995 		 * - the fact that the address of the array and its size never
25996 		 *   changes
25997 		 * - the atomic assignment of the elements of the array
25998 		 */
25999 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26000 			priv = B_TRUE;
26001 		} else {
26002 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26003 				if (requested_port ==
26004 				    tcps->tcps_g_epriv_ports[i]) {
26005 					priv = B_TRUE;
26006 					break;
26007 				}
26008 			}
26009 		}
26010 		if (priv) {
26011 			if (secpolicy_net_privaddr(cr, requested_port,
26012 			    IPPROTO_TCP) != 0) {
26013 				if (tcp->tcp_debug) {
26014 					(void) strlog(TCP_MOD_ID, 0, 1,
26015 					    SL_ERROR|SL_TRACE,
26016 					    "tcp_bind: no priv for port %d",
26017 					    requested_port);
26018 				}
26019 				return (-TACCES);
26020 			}
26021 		}
26022 		user_specified = B_TRUE;
26023 
26024 		connp = tcp->tcp_connp;
26025 		if (is_system_labeled()) {
26026 			zone = crgetzone(cr);
26027 			addrtype = tsol_mlp_addr_type(
26028 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
26029 			    IPV6_VERSION, &v6addr,
26030 			    tcps->tcps_netstack->netstack_ip);
26031 			if (addrtype == mlptSingle) {
26032 				return (-TNOADDR);
26033 			}
26034 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26035 			    requested_port, addrtype);
26036 		}
26037 	}
26038 
26039 	if (mlptype != mlptSingle) {
26040 		if (secpolicy_net_bindmlp(cr) != 0) {
26041 			if (tcp->tcp_debug) {
26042 				(void) strlog(TCP_MOD_ID, 0, 1,
26043 				    SL_ERROR|SL_TRACE,
26044 				    "tcp_bind: no priv for multilevel port %d",
26045 				    requested_port);
26046 			}
26047 			return (-TACCES);
26048 		}
26049 
26050 		/*
26051 		 * If we're specifically binding a shared IP address and the
26052 		 * port is MLP on shared addresses, then check to see if this
26053 		 * zone actually owns the MLP.  Reject if not.
26054 		 */
26055 		if (mlptype == mlptShared && addrtype == mlptShared) {
26056 			/*
26057 			 * No need to handle exclusive-stack zones since
26058 			 * ALL_ZONES only applies to the shared stack.
26059 			 */
26060 			zoneid_t mlpzone;
26061 
26062 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26063 			    htons(mlp_port));
26064 			if (connp->conn_zoneid != mlpzone) {
26065 				if (tcp->tcp_debug) {
26066 					(void) strlog(TCP_MOD_ID, 0, 1,
26067 					    SL_ERROR|SL_TRACE,
26068 					    "tcp_bind: attempt to bind port "
26069 					    "%d on shared addr in zone %d "
26070 					    "(should be %d)",
26071 					    mlp_port, connp->conn_zoneid,
26072 					    mlpzone);
26073 				}
26074 				return (-TACCES);
26075 			}
26076 		}
26077 
26078 		if (!user_specified) {
26079 			int err;
26080 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26081 			    requested_port, B_TRUE);
26082 			if (err != 0) {
26083 				if (tcp->tcp_debug) {
26084 					(void) strlog(TCP_MOD_ID, 0, 1,
26085 					    SL_ERROR|SL_TRACE,
26086 					    "tcp_bind: cannot establish anon "
26087 					    "MLP for port %d",
26088 					    requested_port);
26089 				}
26090 				return (err);
26091 			}
26092 			connp->conn_anon_port = B_TRUE;
26093 		}
26094 		connp->conn_mlp_type = mlptype;
26095 	}
26096 
26097 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26098 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26099 
26100 	if (allocated_port == 0) {
26101 		connp->conn_mlp_type = mlptSingle;
26102 		if (connp->conn_anon_port) {
26103 			connp->conn_anon_port = B_FALSE;
26104 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26105 			    requested_port, B_FALSE);
26106 		}
26107 		if (bind_to_req_port_only) {
26108 			if (tcp->tcp_debug) {
26109 				(void) strlog(TCP_MOD_ID, 0, 1,
26110 				    SL_ERROR|SL_TRACE,
26111 				    "tcp_bind: requested addr busy");
26112 			}
26113 			return (-TADDRBUSY);
26114 		} else {
26115 			/* If we are out of ports, fail the bind. */
26116 			if (tcp->tcp_debug) {
26117 				(void) strlog(TCP_MOD_ID, 0, 1,
26118 				    SL_ERROR|SL_TRACE,
26119 				    "tcp_bind: out of ports?");
26120 			}
26121 			return (-TNOADDR);
26122 		}
26123 	}
26124 
26125 	/* Pass the allocated port back */
26126 	*requested_port_ptr = allocated_port;
26127 	return (0);
26128 }
26129 
26130 static int
26131 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26132     boolean_t bind_to_req_port_only)
26133 {
26134 	tcp_t	*tcp = connp->conn_tcp;
26135 	sin_t	*sin;
26136 	sin6_t  *sin6;
26137 	in_port_t requested_port;
26138 	ipaddr_t	v4addr;
26139 	in6_addr_t	v6addr;
26140 	uint_t	ipversion;
26141 	int	error = 0;
26142 
26143 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26144 
26145 	if (tcp->tcp_state == TCPS_BOUND) {
26146 		return (0);
26147 	} else if (tcp->tcp_state > TCPS_BOUND) {
26148 		if (tcp->tcp_debug) {
26149 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26150 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26151 		}
26152 		return (-TOUTSTATE);
26153 	}
26154 
26155 	ASSERT(sa != NULL && len != 0);
26156 
26157 	if (!OK_32PTR((char *)sa)) {
26158 		if (tcp->tcp_debug) {
26159 			(void) strlog(TCP_MOD_ID, 0, 1,
26160 			    SL_ERROR|SL_TRACE,
26161 			    "tcp_bind: bad address parameter, "
26162 			    "address %p, len %d",
26163 			    (void *)sa, len);
26164 		}
26165 		return (-TPROTO);
26166 	}
26167 
26168 	switch (len) {
26169 	case sizeof (sin_t):	/* Complete IPv4 address */
26170 		sin = (sin_t *)sa;
26171 		/*
26172 		 * With sockets sockfs will accept bogus sin_family in
26173 		 * bind() and replace it with the family used in the socket
26174 		 * call.
26175 		 */
26176 		if (sin->sin_family != AF_INET ||
26177 		    tcp->tcp_family != AF_INET) {
26178 			return (EAFNOSUPPORT);
26179 		}
26180 		requested_port = ntohs(sin->sin_port);
26181 		ipversion = IPV4_VERSION;
26182 		v4addr = sin->sin_addr.s_addr;
26183 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
26184 		break;
26185 
26186 	case sizeof (sin6_t): /* Complete IPv6 address */
26187 		sin6 = (sin6_t *)sa;
26188 		if (sin6->sin6_family != AF_INET6 ||
26189 		    tcp->tcp_family != AF_INET6) {
26190 			return (EAFNOSUPPORT);
26191 		}
26192 		requested_port = ntohs(sin6->sin6_port);
26193 		ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
26194 		    IPV4_VERSION : IPV6_VERSION;
26195 		v6addr = sin6->sin6_addr;
26196 		break;
26197 
26198 	default:
26199 		if (tcp->tcp_debug) {
26200 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26201 			    "tcp_bind: bad address length, %d", len);
26202 		}
26203 		return (EAFNOSUPPORT);
26204 		/* return (-TBADADDR); */
26205 	}
26206 
26207 	tcp->tcp_bound_source_v6 = v6addr;
26208 
26209 	/* Check for change in ipversion */
26210 	if (tcp->tcp_ipversion != ipversion) {
26211 		ASSERT(tcp->tcp_family == AF_INET6);
26212 		error = (ipversion == IPV6_VERSION) ?
26213 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
26214 		if (error) {
26215 			return (ENOMEM);
26216 		}
26217 	}
26218 
26219 	/*
26220 	 * Initialize family specific fields. Copy of the src addr.
26221 	 * in tcp_t is needed for the lookup funcs.
26222 	 */
26223 	if (tcp->tcp_ipversion == IPV6_VERSION) {
26224 		tcp->tcp_ip6h->ip6_src = v6addr;
26225 	} else {
26226 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
26227 	}
26228 	tcp->tcp_ip_src_v6 = v6addr;
26229 
26230 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
26231 
26232 	error = tcp_bind_select_lport(tcp, &requested_port,
26233 	    bind_to_req_port_only, cr);
26234 
26235 	return (error);
26236 }
26237 
26238 /*
26239  * Return unix error is tli error is TSYSERR, otherwise return a negative
26240  * tli error.
26241  */
26242 int
26243 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26244     boolean_t bind_to_req_port_only)
26245 {
26246 	int error;
26247 	tcp_t *tcp = connp->conn_tcp;
26248 
26249 	if (tcp->tcp_state >= TCPS_BOUND) {
26250 		if (tcp->tcp_debug) {
26251 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
26252 			    "tcp_bind: bad state, %d", tcp->tcp_state);
26253 		}
26254 		return (-TOUTSTATE);
26255 	}
26256 
26257 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
26258 	if (error != 0)
26259 		return (error);
26260 
26261 	ASSERT(tcp->tcp_state == TCPS_BOUND);
26262 
26263 	tcp->tcp_conn_req_max = 0;
26264 
26265 	if (tcp->tcp_family == AF_INET6) {
26266 		ASSERT(tcp->tcp_connp->conn_af_isv6);
26267 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
26268 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
26269 	} else {
26270 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
26271 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
26272 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
26273 	}
26274 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
26275 }
26276 
26277 int
26278 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
26279     socklen_t len, cred_t *cr)
26280 {
26281 	int 		error;
26282 	conn_t		*connp = (conn_t *)proto_handle;
26283 	squeue_t	*sqp = connp->conn_sqp;
26284 
26285 	/* All Solaris components should pass a cred for this operation. */
26286 	ASSERT(cr != NULL);
26287 
26288 	ASSERT(sqp != NULL);
26289 	ASSERT(connp->conn_upper_handle != NULL);
26290 
26291 	error = squeue_synch_enter(sqp, connp, NULL);
26292 	if (error != 0) {
26293 		/* failed to enter */
26294 		return (ENOSR);
26295 	}
26296 
26297 	/* binding to a NULL address really means unbind */
26298 	if (sa == NULL) {
26299 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
26300 			error = tcp_do_unbind(connp);
26301 		else
26302 			error = EINVAL;
26303 	} else {
26304 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
26305 	}
26306 
26307 	squeue_synch_exit(sqp, connp);
26308 
26309 	if (error < 0) {
26310 		if (error == -TOUTSTATE)
26311 			error = EINVAL;
26312 		else
26313 			error = proto_tlitosyserr(-error);
26314 	}
26315 
26316 	return (error);
26317 }
26318 
26319 /*
26320  * If the return value from this function is positive, it's a UNIX error.
26321  * Otherwise, if it's negative, then the absolute value is a TLI error.
26322  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
26323  */
26324 int
26325 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
26326     cred_t *cr, pid_t pid)
26327 {
26328 	tcp_t		*tcp = connp->conn_tcp;
26329 	sin_t		*sin = (sin_t *)sa;
26330 	sin6_t		*sin6 = (sin6_t *)sa;
26331 	ipaddr_t	*dstaddrp;
26332 	in_port_t	dstport;
26333 	uint_t		srcid;
26334 	int		error = 0;
26335 
26336 	switch (len) {
26337 	default:
26338 		/*
26339 		 * Should never happen
26340 		 */
26341 		return (EINVAL);
26342 
26343 	case sizeof (sin_t):
26344 		sin = (sin_t *)sa;
26345 		if (sin->sin_port == 0) {
26346 			return (-TBADADDR);
26347 		}
26348 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
26349 			return (EAFNOSUPPORT);
26350 		}
26351 		break;
26352 
26353 	case sizeof (sin6_t):
26354 		sin6 = (sin6_t *)sa;
26355 		if (sin6->sin6_port == 0) {
26356 			return (-TBADADDR);
26357 		}
26358 		break;
26359 	}
26360 	/*
26361 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
26362 	 * make sure that the template IP header in the tcp structure is an
26363 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
26364 	 * need to this before we call tcp_bindi() so that the port lookup
26365 	 * code will look for ports in the correct port space (IPv4 and
26366 	 * IPv6 have separate port spaces).
26367 	 */
26368 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
26369 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26370 		int err = 0;
26371 
26372 		err = tcp_header_init_ipv4(tcp);
26373 			if (err != 0) {
26374 				error = ENOMEM;
26375 				goto connect_failed;
26376 			}
26377 		if (tcp->tcp_lport != 0)
26378 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
26379 	}
26380 
26381 	switch (tcp->tcp_state) {
26382 	case TCPS_LISTEN:
26383 		/*
26384 		 * Listening sockets are not allowed to issue connect().
26385 		 */
26386 		if (IPCL_IS_NONSTR(connp))
26387 			return (EOPNOTSUPP);
26388 		/* FALLTHRU */
26389 	case TCPS_IDLE:
26390 		/*
26391 		 * We support quick connect, refer to comments in
26392 		 * tcp_connect_*()
26393 		 */
26394 		/* FALLTHRU */
26395 	case TCPS_BOUND:
26396 		if (tcp->tcp_family == AF_INET6) {
26397 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
26398 				return (tcp_connect_ipv6(tcp,
26399 				    &sin6->sin6_addr,
26400 				    sin6->sin6_port, sin6->sin6_flowinfo,
26401 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
26402 				    cr, pid));
26403 			}
26404 			/*
26405 			 * Destination adress is mapped IPv6 address.
26406 			 * Source bound address should be unspecified or
26407 			 * IPv6 mapped address as well.
26408 			 */
26409 			if (!IN6_IS_ADDR_UNSPECIFIED(
26410 			    &tcp->tcp_bound_source_v6) &&
26411 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
26412 				return (EADDRNOTAVAIL);
26413 			}
26414 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
26415 			dstport = sin6->sin6_port;
26416 			srcid = sin6->__sin6_src_id;
26417 		} else {
26418 			dstaddrp = &sin->sin_addr.s_addr;
26419 			dstport = sin->sin_port;
26420 			srcid = 0;
26421 		}
26422 
26423 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
26424 		    pid);
26425 		break;
26426 	default:
26427 		return (-TOUTSTATE);
26428 	}
26429 	/*
26430 	 * Note: Code below is the "failure" case
26431 	 */
26432 connect_failed:
26433 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26434 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26435 	return (error);
26436 }
26437 
26438 int
26439 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
26440     socklen_t len, sock_connid_t *id, cred_t *cr)
26441 {
26442 	conn_t		*connp = (conn_t *)proto_handle;
26443 	tcp_t		*tcp = connp->conn_tcp;
26444 	squeue_t	*sqp = connp->conn_sqp;
26445 	int		error;
26446 
26447 	ASSERT(connp->conn_upper_handle != NULL);
26448 
26449 	/* All Solaris components should pass a cred for this operation. */
26450 	ASSERT(cr != NULL);
26451 
26452 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
26453 	if (error != 0) {
26454 		return (error);
26455 	}
26456 
26457 	error = squeue_synch_enter(sqp, connp, NULL);
26458 	if (error != 0) {
26459 		/* failed to enter */
26460 		return (ENOSR);
26461 	}
26462 
26463 	/*
26464 	 * TCP supports quick connect, so no need to do an implicit bind
26465 	 */
26466 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
26467 	if (error == 0) {
26468 		*id = connp->conn_tcp->tcp_connid;
26469 	} else if (error < 0) {
26470 		if (error == -TOUTSTATE) {
26471 			switch (connp->conn_tcp->tcp_state) {
26472 			case TCPS_SYN_SENT:
26473 				error = EALREADY;
26474 				break;
26475 			case TCPS_ESTABLISHED:
26476 				error = EISCONN;
26477 				break;
26478 			case TCPS_LISTEN:
26479 				error = EOPNOTSUPP;
26480 				break;
26481 			default:
26482 				error = EINVAL;
26483 				break;
26484 			}
26485 		} else {
26486 			error = proto_tlitosyserr(-error);
26487 		}
26488 	}
26489 
26490 	if (tcp->tcp_loopback) {
26491 		struct sock_proto_props sopp;
26492 
26493 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
26494 		sopp.sopp_loopback = B_TRUE;
26495 
26496 		(*connp->conn_upcalls->su_set_proto_props)(
26497 		    connp->conn_upper_handle, &sopp);
26498 	}
26499 done:
26500 	squeue_synch_exit(sqp, connp);
26501 
26502 	return ((error == 0) ? EINPROGRESS : error);
26503 }
26504 
26505 /* ARGSUSED */
26506 sock_lower_handle_t
26507 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
26508     uint_t *smodep, int *errorp, int flags, cred_t *credp)
26509 {
26510 	conn_t		*connp;
26511 	boolean_t	isv6 = family == AF_INET6;
26512 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
26513 	    (proto != 0 && proto != IPPROTO_TCP)) {
26514 		*errorp = EPROTONOSUPPORT;
26515 		return (NULL);
26516 	}
26517 
26518 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
26519 	if (connp == NULL) {
26520 		return (NULL);
26521 	}
26522 
26523 	/*
26524 	 * Put the ref for TCP. Ref for IP was already put
26525 	 * by ipcl_conn_create. Also Make the conn_t globally
26526 	 * visible to walkers
26527 	 */
26528 	mutex_enter(&connp->conn_lock);
26529 	CONN_INC_REF_LOCKED(connp);
26530 	ASSERT(connp->conn_ref == 2);
26531 	connp->conn_state_flags &= ~CONN_INCIPIENT;
26532 
26533 	connp->conn_flags |= IPCL_NONSTR;
26534 	mutex_exit(&connp->conn_lock);
26535 
26536 	ASSERT(errorp != NULL);
26537 	*errorp = 0;
26538 	*sock_downcalls = &sock_tcp_downcalls;
26539 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
26540 	    SM_SENDFILESUPP;
26541 
26542 	return ((sock_lower_handle_t)connp);
26543 }
26544 
26545 /* ARGSUSED */
26546 void
26547 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
26548     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
26549 {
26550 	conn_t *connp = (conn_t *)proto_handle;
26551 	struct sock_proto_props sopp;
26552 
26553 	ASSERT(connp->conn_upper_handle == NULL);
26554 
26555 	/* All Solaris components should pass a cred for this operation. */
26556 	ASSERT(cr != NULL);
26557 
26558 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
26559 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
26560 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
26561 
26562 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
26563 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
26564 	sopp.sopp_maxpsz = INFPSZ;
26565 	sopp.sopp_maxblk = INFPSZ;
26566 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
26567 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
26568 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
26569 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
26570 	    tcp_rinfo.mi_minpsz;
26571 
26572 	connp->conn_upcalls = sock_upcalls;
26573 	connp->conn_upper_handle = sock_handle;
26574 
26575 	ASSERT(connp->conn_tcp->tcp_recv_hiwater != 0 &&
26576 	    connp->conn_tcp->tcp_recv_hiwater == connp->conn_tcp->tcp_rwnd);
26577 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
26578 }
26579 
26580 /* ARGSUSED */
26581 int
26582 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
26583 {
26584 	conn_t *connp = (conn_t *)proto_handle;
26585 
26586 	ASSERT(connp->conn_upper_handle != NULL);
26587 
26588 	/* All Solaris components should pass a cred for this operation. */
26589 	ASSERT(cr != NULL);
26590 
26591 	tcp_close_common(connp, flags);
26592 
26593 	ip_free_helper_stream(connp);
26594 
26595 	/*
26596 	 * Drop IP's reference on the conn. This is the last reference
26597 	 * on the connp if the state was less than established. If the
26598 	 * connection has gone into timewait state, then we will have
26599 	 * one ref for the TCP and one more ref (total of two) for the
26600 	 * classifier connected hash list (a timewait connections stays
26601 	 * in connected hash till closed).
26602 	 *
26603 	 * We can't assert the references because there might be other
26604 	 * transient reference places because of some walkers or queued
26605 	 * packets in squeue for the timewait state.
26606 	 */
26607 	CONN_DEC_REF(connp);
26608 	return (0);
26609 }
26610 
26611 /* ARGSUSED */
26612 int
26613 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
26614     cred_t *cr)
26615 {
26616 	tcp_t		*tcp;
26617 	uint32_t	msize;
26618 	conn_t *connp = (conn_t *)proto_handle;
26619 	int32_t		tcpstate;
26620 
26621 	/* All Solaris components should pass a cred for this operation. */
26622 	ASSERT(cr != NULL);
26623 
26624 	ASSERT(connp->conn_ref >= 2);
26625 	ASSERT(connp->conn_upper_handle != NULL);
26626 
26627 	if (msg->msg_controllen != 0) {
26628 		freemsg(mp);
26629 		return (EOPNOTSUPP);
26630 	}
26631 
26632 	switch (DB_TYPE(mp)) {
26633 	case M_DATA:
26634 		tcp = connp->conn_tcp;
26635 		ASSERT(tcp != NULL);
26636 
26637 		tcpstate = tcp->tcp_state;
26638 		if (tcpstate < TCPS_ESTABLISHED) {
26639 			freemsg(mp);
26640 			/*
26641 			 * We return ENOTCONN if the endpoint is trying to
26642 			 * connect or has never been connected, and EPIPE if it
26643 			 * has been disconnected. The connection id helps us
26644 			 * distinguish between the last two cases.
26645 			 */
26646 			return ((tcpstate == TCPS_SYN_SENT) ? ENOTCONN :
26647 			    ((tcp->tcp_connid > 0) ? EPIPE : ENOTCONN));
26648 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
26649 			freemsg(mp);
26650 			return (EPIPE);
26651 		}
26652 
26653 		msize = msgdsize(mp);
26654 
26655 		mutex_enter(&tcp->tcp_non_sq_lock);
26656 		tcp->tcp_squeue_bytes += msize;
26657 		/*
26658 		 * Squeue Flow Control
26659 		 */
26660 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
26661 			tcp_setqfull(tcp);
26662 		}
26663 		mutex_exit(&tcp->tcp_non_sq_lock);
26664 
26665 		/*
26666 		 * The application may pass in an address in the msghdr, but
26667 		 * we ignore the address on connection-oriented sockets.
26668 		 * Just like BSD this code does not generate an error for
26669 		 * TCP (a CONNREQUIRED socket) when sending to an address
26670 		 * passed in with sendto/sendmsg. Instead the data is
26671 		 * delivered on the connection as if no address had been
26672 		 * supplied.
26673 		 */
26674 		CONN_INC_REF(connp);
26675 
26676 		if (msg->msg_flags & MSG_OOB) {
26677 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
26678 			    tcp_output_urgent, connp, tcp_squeue_flag,
26679 			    SQTAG_TCP_OUTPUT);
26680 		} else {
26681 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
26682 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
26683 		}
26684 
26685 		return (0);
26686 
26687 	default:
26688 		ASSERT(0);
26689 	}
26690 
26691 	freemsg(mp);
26692 	return (0);
26693 }
26694 
26695 /* ARGSUSED */
26696 void
26697 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
26698 {
26699 	int len;
26700 	uint32_t msize;
26701 	conn_t *connp = (conn_t *)arg;
26702 	tcp_t *tcp = connp->conn_tcp;
26703 
26704 	msize = msgdsize(mp);
26705 
26706 	len = msize - 1;
26707 	if (len < 0) {
26708 		freemsg(mp);
26709 		return;
26710 	}
26711 
26712 	/*
26713 	 * Try to force urgent data out on the wire. Even if we have unsent
26714 	 * data this will at least send the urgent flag.
26715 	 * XXX does not handle more flag correctly.
26716 	 */
26717 	len += tcp->tcp_unsent;
26718 	len += tcp->tcp_snxt;
26719 	tcp->tcp_urg = len;
26720 	tcp->tcp_valid_bits |= TCP_URG_VALID;
26721 
26722 	/* Bypass tcp protocol for fused tcp loopback */
26723 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
26724 		return;
26725 
26726 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
26727 	if (DB_TYPE(mp) != M_DATA) {
26728 		mblk_t *mp1 = mp;
26729 		ASSERT(!IPCL_IS_NONSTR(connp));
26730 		mp = mp->b_cont;
26731 		freeb(mp1);
26732 	}
26733 	tcp_wput_data(tcp, mp, B_TRUE);
26734 }
26735 
26736 /* ARGSUSED */
26737 int
26738 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26739     socklen_t *addrlenp, cred_t *cr)
26740 {
26741 	conn_t	*connp = (conn_t *)proto_handle;
26742 	tcp_t	*tcp = connp->conn_tcp;
26743 
26744 	ASSERT(connp->conn_upper_handle != NULL);
26745 	/* All Solaris components should pass a cred for this operation. */
26746 	ASSERT(cr != NULL);
26747 
26748 	ASSERT(tcp != NULL);
26749 
26750 	return (tcp_do_getpeername(tcp, addr, addrlenp));
26751 }
26752 
26753 /* ARGSUSED */
26754 int
26755 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
26756     socklen_t *addrlenp, cred_t *cr)
26757 {
26758 	conn_t	*connp = (conn_t *)proto_handle;
26759 	tcp_t	*tcp = connp->conn_tcp;
26760 
26761 	/* All Solaris components should pass a cred for this operation. */
26762 	ASSERT(cr != NULL);
26763 
26764 	ASSERT(connp->conn_upper_handle != NULL);
26765 
26766 	return (tcp_do_getsockname(tcp, addr, addrlenp));
26767 }
26768 
26769 /*
26770  * tcp_fallback
26771  *
26772  * A direct socket is falling back to using STREAMS. The queue
26773  * that is being passed down was created using tcp_open() with
26774  * the SO_FALLBACK flag set. As a result, the queue is not
26775  * associated with a conn, and the q_ptrs instead contain the
26776  * dev and minor area that should be used.
26777  *
26778  * The 'issocket' flag indicates whether the FireEngine
26779  * optimizations should be used. The common case would be that
26780  * optimizations are enabled, and they might be subsequently
26781  * disabled using the _SIOCSOCKFALLBACK ioctl.
26782  */
26783 
26784 /*
26785  * An active connection is falling back to TPI. Gather all the information
26786  * required by the STREAM head and TPI sonode and send it up.
26787  */
26788 void
26789 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
26790     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
26791 {
26792 	conn_t			*connp = tcp->tcp_connp;
26793 	struct stroptions	*stropt;
26794 	struct T_capability_ack tca;
26795 	struct sockaddr_in6	laddr, faddr;
26796 	socklen_t 		laddrlen, faddrlen;
26797 	short			opts;
26798 	int			error;
26799 	mblk_t			*mp;
26800 
26801 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
26802 	connp->conn_minor_arena = WR(q)->q_ptr;
26803 
26804 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
26805 
26806 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
26807 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
26808 
26809 	WR(q)->q_qinfo = &tcp_sock_winit;
26810 
26811 	if (!issocket)
26812 		tcp_use_pure_tpi(tcp);
26813 
26814 	/*
26815 	 * free the helper stream
26816 	 */
26817 	ip_free_helper_stream(connp);
26818 
26819 	/*
26820 	 * Notify the STREAM head about options
26821 	 */
26822 	DB_TYPE(stropt_mp) = M_SETOPTS;
26823 	stropt = (struct stroptions *)stropt_mp->b_rptr;
26824 	stropt_mp->b_wptr += sizeof (struct stroptions);
26825 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
26826 
26827 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
26828 	    tcp->tcp_tcps->tcps_wroff_xtra);
26829 	if (tcp->tcp_snd_sack_ok)
26830 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
26831 	stropt->so_hiwat = tcp->tcp_recv_hiwater;
26832 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
26833 
26834 	putnext(RD(q), stropt_mp);
26835 
26836 	/*
26837 	 * Collect the information needed to sync with the sonode
26838 	 */
26839 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
26840 
26841 	laddrlen = faddrlen = sizeof (sin6_t);
26842 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
26843 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
26844 	if (error != 0)
26845 		faddrlen = 0;
26846 
26847 	opts = 0;
26848 	if (tcp->tcp_oobinline)
26849 		opts |= SO_OOBINLINE;
26850 	if (tcp->tcp_dontroute)
26851 		opts |= SO_DONTROUTE;
26852 
26853 	/*
26854 	 * Notify the socket that the protocol is now quiescent,
26855 	 * and it's therefore safe move data from the socket
26856 	 * to the stream head.
26857 	 */
26858 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
26859 	    (struct sockaddr *)&laddr, laddrlen,
26860 	    (struct sockaddr *)&faddr, faddrlen, opts);
26861 
26862 	while ((mp = tcp->tcp_rcv_list) != NULL) {
26863 		tcp->tcp_rcv_list = mp->b_next;
26864 		mp->b_next = NULL;
26865 		putnext(q, mp);
26866 	}
26867 	tcp->tcp_rcv_last_head = NULL;
26868 	tcp->tcp_rcv_last_tail = NULL;
26869 	tcp->tcp_rcv_cnt = 0;
26870 }
26871 
26872 /*
26873  * An eager is falling back to TPI. All we have to do is send
26874  * up a T_CONN_IND.
26875  */
26876 void
26877 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
26878 {
26879 	tcp_t *listener = eager->tcp_listener;
26880 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
26881 
26882 	ASSERT(listener != NULL);
26883 	ASSERT(mp != NULL);
26884 
26885 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
26886 
26887 	/*
26888 	 * TLI/XTI applications will get confused by
26889 	 * sending eager as an option since it violates
26890 	 * the option semantics. So remove the eager as
26891 	 * option since TLI/XTI app doesn't need it anyway.
26892 	 */
26893 	if (!direct_sockfs) {
26894 		struct T_conn_ind *conn_ind;
26895 
26896 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
26897 		conn_ind->OPT_length = 0;
26898 		conn_ind->OPT_offset = 0;
26899 	}
26900 
26901 	/*
26902 	 * Sockfs guarantees that the listener will not be closed
26903 	 * during fallback. So we can safely use the listener's queue.
26904 	 */
26905 	putnext(listener->tcp_rq, mp);
26906 }
26907 
26908 int
26909 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
26910     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
26911 {
26912 	tcp_t			*tcp;
26913 	conn_t 			*connp = (conn_t *)proto_handle;
26914 	int			error;
26915 	mblk_t			*stropt_mp;
26916 	mblk_t			*ordrel_mp;
26917 
26918 	tcp = connp->conn_tcp;
26919 
26920 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
26921 	    NULL);
26922 
26923 	/* Pre-allocate the T_ordrel_ind mblk. */
26924 	ASSERT(tcp->tcp_ordrel_mp == NULL);
26925 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
26926 	    STR_NOSIG, NULL);
26927 	ordrel_mp->b_datap->db_type = M_PROTO;
26928 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
26929 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
26930 
26931 	/*
26932 	 * Enter the squeue so that no new packets can come in
26933 	 */
26934 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
26935 	if (error != 0) {
26936 		/* failed to enter, free all the pre-allocated messages. */
26937 		freeb(stropt_mp);
26938 		freeb(ordrel_mp);
26939 		/*
26940 		 * We cannot process the eager, so at least send out a
26941 		 * RST so the peer can reconnect.
26942 		 */
26943 		if (tcp->tcp_listener != NULL) {
26944 			(void) tcp_eager_blowoff(tcp->tcp_listener,
26945 			    tcp->tcp_conn_req_seqnum);
26946 		}
26947 		return (ENOMEM);
26948 	}
26949 
26950 	/*
26951 	 * Both endpoints must be of the same type (either STREAMS or
26952 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
26953 	 * we have to unfuse.
26954 	 */
26955 	if (tcp->tcp_fused)
26956 		tcp_unfuse(tcp);
26957 
26958 	/*
26959 	 * No longer a direct socket
26960 	 */
26961 	connp->conn_flags &= ~IPCL_NONSTR;
26962 	tcp->tcp_ordrel_mp = ordrel_mp;
26963 
26964 	if (tcp->tcp_listener != NULL) {
26965 		/* The eager will deal with opts when accept() is called */
26966 		freeb(stropt_mp);
26967 		tcp_fallback_eager(tcp, direct_sockfs);
26968 	} else {
26969 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
26970 		    quiesced_cb);
26971 	}
26972 
26973 	/*
26974 	 * There should be atleast two ref's (IP + TCP)
26975 	 */
26976 	ASSERT(connp->conn_ref >= 2);
26977 	squeue_synch_exit(connp->conn_sqp, connp);
26978 
26979 	return (0);
26980 }
26981 
26982 /* ARGSUSED */
26983 static void
26984 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
26985 {
26986 	conn_t 	*connp = (conn_t *)arg;
26987 	tcp_t	*tcp = connp->conn_tcp;
26988 
26989 	freemsg(mp);
26990 
26991 	if (tcp->tcp_fused)
26992 		tcp_unfuse(tcp);
26993 
26994 	if (tcp_xmit_end(tcp) != 0) {
26995 		/*
26996 		 * We were crossing FINs and got a reset from
26997 		 * the other side. Just ignore it.
26998 		 */
26999 		if (tcp->tcp_debug) {
27000 			(void) strlog(TCP_MOD_ID, 0, 1,
27001 			    SL_ERROR|SL_TRACE,
27002 			    "tcp_shutdown_output() out of state %s",
27003 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27004 		}
27005 	}
27006 }
27007 
27008 /* ARGSUSED */
27009 int
27010 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27011 {
27012 	conn_t  *connp = (conn_t *)proto_handle;
27013 	tcp_t   *tcp = connp->conn_tcp;
27014 
27015 	ASSERT(connp->conn_upper_handle != NULL);
27016 
27017 	/* All Solaris components should pass a cred for this operation. */
27018 	ASSERT(cr != NULL);
27019 
27020 	/*
27021 	 * X/Open requires that we check the connected state.
27022 	 */
27023 	if (tcp->tcp_state < TCPS_SYN_SENT)
27024 		return (ENOTCONN);
27025 
27026 	/* shutdown the send side */
27027 	if (how != SHUT_RD) {
27028 		mblk_t *bp;
27029 
27030 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27031 		CONN_INC_REF(connp);
27032 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27033 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27034 
27035 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27036 		    SOCK_OPCTL_SHUT_SEND, 0);
27037 	}
27038 
27039 	/* shutdown the recv side */
27040 	if (how != SHUT_WR)
27041 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27042 		    SOCK_OPCTL_SHUT_RECV, 0);
27043 
27044 	return (0);
27045 }
27046 
27047 /*
27048  * SOP_LISTEN() calls into tcp_listen().
27049  */
27050 /* ARGSUSED */
27051 int
27052 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27053 {
27054 	conn_t	*connp = (conn_t *)proto_handle;
27055 	int 	error;
27056 	squeue_t *sqp = connp->conn_sqp;
27057 
27058 	ASSERT(connp->conn_upper_handle != NULL);
27059 
27060 	/* All Solaris components should pass a cred for this operation. */
27061 	ASSERT(cr != NULL);
27062 
27063 	error = squeue_synch_enter(sqp, connp, NULL);
27064 	if (error != 0) {
27065 		/* failed to enter */
27066 		return (ENOBUFS);
27067 	}
27068 
27069 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
27070 	if (error == 0) {
27071 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27072 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27073 	} else if (error < 0) {
27074 		if (error == -TOUTSTATE)
27075 			error = EINVAL;
27076 		else
27077 			error = proto_tlitosyserr(-error);
27078 	}
27079 	squeue_synch_exit(sqp, connp);
27080 	return (error);
27081 }
27082 
27083 static int
27084 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
27085     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
27086 {
27087 	tcp_t		*tcp = connp->conn_tcp;
27088 	int		error = 0;
27089 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27090 
27091 	/* All Solaris components should pass a cred for this operation. */
27092 	ASSERT(cr != NULL);
27093 
27094 	if (tcp->tcp_state >= TCPS_BOUND) {
27095 		if ((tcp->tcp_state == TCPS_BOUND ||
27096 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
27097 			/*
27098 			 * Handle listen() increasing backlog.
27099 			 * This is more "liberal" then what the TPI spec
27100 			 * requires but is needed to avoid a t_unbind
27101 			 * when handling listen() since the port number
27102 			 * might be "stolen" between the unbind and bind.
27103 			 */
27104 			goto do_listen;
27105 		}
27106 		if (tcp->tcp_debug) {
27107 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27108 			    "tcp_listen: bad state, %d", tcp->tcp_state);
27109 		}
27110 		return (-TOUTSTATE);
27111 	} else {
27112 		if (sa == NULL) {
27113 			sin6_t	addr;
27114 			sin_t *sin;
27115 			sin6_t *sin6;
27116 
27117 			ASSERT(IPCL_IS_NONSTR(connp));
27118 
27119 			/* Do an implicit bind: Request for a generic port. */
27120 			if (tcp->tcp_family == AF_INET) {
27121 				len = sizeof (sin_t);
27122 				sin = (sin_t *)&addr;
27123 				*sin = sin_null;
27124 				sin->sin_family = AF_INET;
27125 			} else {
27126 				ASSERT(tcp->tcp_family == AF_INET6);
27127 				len = sizeof (sin6_t);
27128 				sin6 = (sin6_t *)&addr;
27129 				*sin6 = sin6_null;
27130 				sin6->sin6_family = AF_INET6;
27131 			}
27132 			sa = (struct sockaddr *)&addr;
27133 		}
27134 
27135 		error = tcp_bind_check(connp, sa, len, cr,
27136 		    bind_to_req_port_only);
27137 		if (error)
27138 			return (error);
27139 		/* Fall through and do the fanout insertion */
27140 	}
27141 
27142 do_listen:
27143 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
27144 	tcp->tcp_conn_req_max = backlog;
27145 	if (tcp->tcp_conn_req_max) {
27146 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
27147 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
27148 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
27149 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
27150 		/*
27151 		 * If this is a listener, do not reset the eager list
27152 		 * and other stuffs.  Note that we don't check if the
27153 		 * existing eager list meets the new tcp_conn_req_max
27154 		 * requirement.
27155 		 */
27156 		if (tcp->tcp_state != TCPS_LISTEN) {
27157 			tcp->tcp_state = TCPS_LISTEN;
27158 			/* Initialize the chain. Don't need the eager_lock */
27159 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
27160 			tcp->tcp_eager_next_drop_q0 = tcp;
27161 			tcp->tcp_eager_prev_drop_q0 = tcp;
27162 			tcp->tcp_second_ctimer_threshold =
27163 			    tcps->tcps_ip_abort_linterval;
27164 		}
27165 	}
27166 
27167 	/*
27168 	 * We can call ip_bind directly, the processing continues
27169 	 * in tcp_post_ip_bind().
27170 	 *
27171 	 * We need to make sure that the conn_recv is set to a non-null
27172 	 * value before we insert the conn into the classifier table.
27173 	 * This is to avoid a race with an incoming packet which does an
27174 	 * ipcl_classify().
27175 	 */
27176 	connp->conn_recv = tcp_conn_request;
27177 	if (tcp->tcp_family == AF_INET) {
27178 		error = ip_proto_bind_laddr_v4(connp, NULL,
27179 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
27180 	} else {
27181 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27182 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
27183 	}
27184 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27185 }
27186 
27187 void
27188 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
27189 {
27190 	conn_t  *connp = (conn_t *)proto_handle;
27191 	tcp_t	*tcp = connp->conn_tcp;
27192 	mblk_t *mp;
27193 	int error;
27194 
27195 	ASSERT(connp->conn_upper_handle != NULL);
27196 
27197 	/*
27198 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
27199 	 * is currently running.
27200 	 */
27201 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27202 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
27203 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
27204 		return;
27205 	}
27206 	tcp->tcp_rsrv_mp = NULL;
27207 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27208 
27209 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
27210 	ASSERT(error == 0);
27211 
27212 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
27213 	tcp->tcp_rsrv_mp = mp;
27214 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
27215 
27216 	if (tcp->tcp_fused) {
27217 		tcp_fuse_backenable(tcp);
27218 	} else {
27219 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
27220 		/*
27221 		 * Send back a window update immediately if TCP is above
27222 		 * ESTABLISHED state and the increase of the rcv window
27223 		 * that the other side knows is at least 1 MSS after flow
27224 		 * control is lifted.
27225 		 */
27226 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
27227 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
27228 			tcp_xmit_ctl(NULL, tcp,
27229 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
27230 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
27231 		}
27232 	}
27233 
27234 	squeue_synch_exit(connp->conn_sqp, connp);
27235 }
27236 
27237 /* ARGSUSED */
27238 int
27239 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
27240     int mode, int32_t *rvalp, cred_t *cr)
27241 {
27242 	conn_t  	*connp = (conn_t *)proto_handle;
27243 	int		error;
27244 
27245 	ASSERT(connp->conn_upper_handle != NULL);
27246 
27247 	/* All Solaris components should pass a cred for this operation. */
27248 	ASSERT(cr != NULL);
27249 
27250 	switch (cmd) {
27251 		case ND_SET:
27252 		case ND_GET:
27253 		case TCP_IOC_DEFAULT_Q:
27254 		case _SIOCSOCKFALLBACK:
27255 		case TCP_IOC_ABORT_CONN:
27256 		case TI_GETPEERNAME:
27257 		case TI_GETMYNAME:
27258 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
27259 			    cmd));
27260 			error = EINVAL;
27261 			break;
27262 		default:
27263 			/*
27264 			 * Pass on to IP using helper stream
27265 			 */
27266 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
27267 			    cmd, arg, mode, cr, rvalp);
27268 			break;
27269 	}
27270 	return (error);
27271 }
27272 
27273 sock_downcalls_t sock_tcp_downcalls = {
27274 	tcp_activate,
27275 	tcp_accept,
27276 	tcp_bind,
27277 	tcp_listen,
27278 	tcp_connect,
27279 	tcp_getpeername,
27280 	tcp_getsockname,
27281 	tcp_getsockopt,
27282 	tcp_setsockopt,
27283 	tcp_sendmsg,
27284 	NULL,
27285 	NULL,
27286 	NULL,
27287 	tcp_shutdown,
27288 	tcp_clr_flowctrl,
27289 	tcp_ioctl,
27290 	tcp_close,
27291 };
27292