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 (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, Joyent Inc. All rights reserved.
25 * Copyright (c) 2011 Nexenta Systems, Inc. All rights reserved.
26 * Copyright (c) 2013, 2016 by Delphix. All rights reserved.
27 * Copyright 2014, OmniTI Computer Consulting, Inc. All rights reserved.
28 */
29 /* Copyright (c) 1990 Mentat Inc. */
30
31 #include <sys/types.h>
32 #include <sys/stream.h>
33 #include <sys/strsun.h>
34 #include <sys/strsubr.h>
35 #include <sys/stropts.h>
36 #include <sys/strlog.h>
37 #define _SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/timod.h>
40 #include <sys/ddi.h>
41 #include <sys/sunddi.h>
42 #include <sys/suntpi.h>
43 #include <sys/xti_inet.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/sdt.h>
47 #include <sys/vtrace.h>
48 #include <sys/kmem.h>
49 #include <sys/ethernet.h>
50 #include <sys/cpuvar.h>
51 #include <sys/dlpi.h>
52 #include <sys/pattr.h>
53 #include <sys/policy.h>
54 #include <sys/priv.h>
55 #include <sys/zone.h>
56 #include <sys/sunldi.h>
57
58 #include <sys/errno.h>
59 #include <sys/signal.h>
60 #include <sys/socket.h>
61 #include <sys/socketvar.h>
62 #include <sys/sockio.h>
63 #include <sys/isa_defs.h>
64 #include <sys/md5.h>
65 #include <sys/random.h>
66 #include <sys/uio.h>
67 #include <sys/systm.h>
68 #include <netinet/in.h>
69 #include <netinet/tcp.h>
70 #include <netinet/ip6.h>
71 #include <netinet/icmp6.h>
72 #include <net/if.h>
73 #include <net/route.h>
74 #include <inet/ipsec_impl.h>
75
76 #include <inet/common.h>
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip_ndp.h>
81 #include <inet/proto_set.h>
82 #include <inet/mib2.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/tcp_cluster.h>
89 #include <inet/udp_impl.h>
90 #include <net/pfkeyv2.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_rts.h>
99 #include <inet/ip_netinfo.h>
100 #include <sys/squeue_impl.h>
101 #include <sys/squeue.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_TCPCONN 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_input_listener(). But briefly, the squeue is picked by
176 * ip_fanout based on the ring or the sender (if loopback).
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 provisions for sockfs by marking tcp_issocket
202 * whenever we have only sockfs on top of TCP. This allows us to skip
203 * putting the tcp in acceptor hash since a sockfs listener can never
204 * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
205 * since eager has already been allocated and the accept now happens
206 * on acceptor STREAM. There is a big blob of comment on top of
207 * tcp_input_listener explaining the new accept. When socket is POP'd,
208 * sockfs sends us an ioctl to mark the fact and we go back to old
209 * behaviour. Once tcp_issocket is unset, its never set for the
210 * life of that connection.
211 *
212 * IPsec notes :
213 *
214 * Since a packet is always executed on the correct TCP perimeter
215 * all IPsec processing is defered to IP including checking new
216 * connections and setting IPSEC policies for new connection. The
217 * only exception is tcp_xmit_listeners_reset() which is called
218 * directly from IP and needs to policy check to see if TH_RST
219 * can be sent out.
220 */
221
222 /*
223 * Values for squeue switch:
224 * 1: SQ_NODRAIN
225 * 2: SQ_PROCESS
226 * 3: SQ_FILL
227 */
228 int tcp_squeue_wput = 2; /* /etc/systems */
229 int tcp_squeue_flag;
230
231 /*
232 * To prevent memory hog, limit the number of entries in tcp_free_list
233 * to 1% of available memory / number of cpus
234 */
235 uint_t tcp_free_list_max_cnt = 0;
236
237 #define TIDUSZ 4096 /* transport interface data unit size */
238
239 /*
240 * Size of acceptor hash list. It has to be a power of 2 for hashing.
241 */
242 #define TCP_ACCEPTOR_FANOUT_SIZE 512
243
244 #ifdef _ILP32
245 #define TCP_ACCEPTOR_HASH(accid) \
246 (((uint_t)(accid) >> 8) & (TCP_ACCEPTOR_FANOUT_SIZE - 1))
247 #else
248 #define TCP_ACCEPTOR_HASH(accid) \
249 ((uint_t)(accid) & (TCP_ACCEPTOR_FANOUT_SIZE - 1))
250 #endif /* _ILP32 */
251
252 /*
253 * Minimum number of connections which can be created per listener. Used
254 * when the listener connection count is in effect.
255 */
256 static uint32_t tcp_min_conn_listener = 2;
257
258 uint32_t tcp_early_abort = 30;
259
260 /* TCP Timer control structure */
261 typedef struct tcpt_s {
262 pfv_t tcpt_pfv; /* The routine we are to call */
263 tcp_t *tcpt_tcp; /* The parameter we are to pass in */
264 } tcpt_t;
265
266 /*
267 * Functions called directly via squeue having a prototype of edesc_t.
268 */
269 void tcp_input_data(void *arg, mblk_t *mp, void *arg2,
270 ip_recv_attr_t *ira);
271 static void tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2,
272 ip_recv_attr_t *dummy);
273
274
275 /* Prototype for TCP functions */
276 static void tcp_random_init(void);
277 int tcp_random(void);
278 static int tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
279 in_port_t dstport, uint_t srcid);
280 static int tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
281 in_port_t dstport, uint32_t flowinfo,
282 uint_t srcid, uint32_t scope_id);
283 static void tcp_iss_init(tcp_t *tcp);
284 static void tcp_reinit(tcp_t *tcp);
285 static void tcp_reinit_values(tcp_t *tcp);
286
287 static int tcp_wsrv(queue_t *q);
288 static void tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa);
289 static void tcp_update_zcopy(tcp_t *tcp);
290 static void tcp_notify(void *, ip_xmit_attr_t *, ixa_notify_type_t,
291 ixa_notify_arg_t);
292 static void *tcp_stack_init(netstackid_t stackid, netstack_t *ns);
293 static void tcp_stack_fini(netstackid_t stackid, void *arg);
294
295 static int tcp_squeue_switch(int);
296
297 static int tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
298 static int tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
299 static int tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
300
301 static void tcp_squeue_add(squeue_t *);
302
303 struct module_info tcp_rinfo = {
304 TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
305 };
306
307 static struct module_info tcp_winfo = {
308 TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
309 };
310
311 /*
312 * Entry points for TCP as a device. The normal case which supports
313 * the TCP functionality.
314 * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
315 */
316 struct qinit tcp_rinitv4 = {
317 NULL, tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
318 };
319
320 struct qinit tcp_rinitv6 = {
321 NULL, tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
322 };
323
324 struct qinit tcp_winit = {
325 tcp_wput, tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
326 };
327
328 /* Initial entry point for TCP in socket mode. */
329 struct qinit tcp_sock_winit = {
330 tcp_wput_sock, tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
331 };
332
333 /* TCP entry point during fallback */
334 struct qinit tcp_fallback_sock_winit = {
335 tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
336 };
337
338 /*
339 * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
340 * an accept. Avoid allocating data structures since eager has already
341 * been created.
342 */
343 struct qinit tcp_acceptor_rinit = {
344 NULL, tcp_rsrv, NULL, tcp_tpi_close_accept, NULL, &tcp_winfo
345 };
346
347 struct qinit tcp_acceptor_winit = {
348 tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
349 };
350
351 /* For AF_INET aka /dev/tcp */
352 struct streamtab tcpinfov4 = {
353 &tcp_rinitv4, &tcp_winit
354 };
355
356 /* For AF_INET6 aka /dev/tcp6 */
357 struct streamtab tcpinfov6 = {
358 &tcp_rinitv6, &tcp_winit
359 };
360
361 /*
362 * Following assumes TPI alignment requirements stay along 32 bit
363 * boundaries
364 */
365 #define ROUNDUP32(x) \
366 (((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
367
368 /* Template for response to info request. */
369 struct T_info_ack tcp_g_t_info_ack = {
370 T_INFO_ACK, /* PRIM_type */
371 0, /* TSDU_size */
372 T_INFINITE, /* ETSDU_size */
373 T_INVALID, /* CDATA_size */
374 T_INVALID, /* DDATA_size */
375 sizeof (sin_t), /* ADDR_size */
376 0, /* OPT_size - not initialized here */
377 TIDUSZ, /* TIDU_size */
378 T_COTS_ORD, /* SERV_type */
379 TCPS_IDLE, /* CURRENT_state */
380 (XPG4_1|EXPINLINE) /* PROVIDER_flag */
381 };
382
383 struct T_info_ack tcp_g_t_info_ack_v6 = {
384 T_INFO_ACK, /* PRIM_type */
385 0, /* TSDU_size */
386 T_INFINITE, /* ETSDU_size */
387 T_INVALID, /* CDATA_size */
388 T_INVALID, /* DDATA_size */
389 sizeof (sin6_t), /* ADDR_size */
390 0, /* OPT_size - not initialized here */
391 TIDUSZ, /* TIDU_size */
392 T_COTS_ORD, /* SERV_type */
393 TCPS_IDLE, /* CURRENT_state */
394 (XPG4_1|EXPINLINE) /* PROVIDER_flag */
395 };
396
397 /*
398 * TCP tunables related declarations. Definitions are in tcp_tunables.c
399 */
400 extern mod_prop_info_t tcp_propinfo_tbl[];
401 extern int tcp_propinfo_count;
402
403 #define IS_VMLOANED_MBLK(mp) \
404 (((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
405
406 uint32_t do_tcpzcopy = 1; /* 0: disable, 1: enable, 2: force */
407
408 /*
409 * Forces all connections to obey the value of the tcps_maxpsz_multiplier
410 * tunable settable via NDD. Otherwise, the per-connection behavior is
411 * determined dynamically during tcp_set_destination(), which is the default.
412 */
413 boolean_t tcp_static_maxpsz = B_FALSE;
414
415 /*
416 * If the receive buffer size is changed, this function is called to update
417 * the upper socket layer on the new delayed receive wake up threshold.
418 */
419 static void
420 tcp_set_recv_threshold(tcp_t *tcp, uint32_t new_rcvthresh)
421 {
422 uint32_t default_threshold = SOCKET_RECVHIWATER >> 3;
423
424 if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
425 conn_t *connp = tcp->tcp_connp;
426 struct sock_proto_props sopp;
427
428 /*
429 * only increase rcvthresh upto default_threshold
430 */
431 if (new_rcvthresh > default_threshold)
432 new_rcvthresh = default_threshold;
433
434 sopp.sopp_flags = SOCKOPT_RCVTHRESH;
435 sopp.sopp_rcvthresh = new_rcvthresh;
436
437 (*connp->conn_upcalls->su_set_proto_props)
438 (connp->conn_upper_handle, &sopp);
439 }
440 }
441
442 /*
443 * Figure out the value of window scale opton. Note that the rwnd is
444 * ASSUMED to be rounded up to the nearest MSS before the calculation.
445 * We cannot find the scale value and then do a round up of tcp_rwnd
446 * because the scale value may not be correct after that.
447 *
448 * Set the compiler flag to make this function inline.
449 */
450 void
451 tcp_set_ws_value(tcp_t *tcp)
452 {
453 int i;
454 uint32_t rwnd = tcp->tcp_rwnd;
455
456 for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
457 i++, rwnd >>= 1)
458 ;
459 tcp->tcp_rcv_ws = i;
460 }
461
462 /*
463 * Remove cached/latched IPsec references.
464 */
465 void
466 tcp_ipsec_cleanup(tcp_t *tcp)
467 {
468 conn_t *connp = tcp->tcp_connp;
469
470 ASSERT(connp->conn_flags & IPCL_TCPCONN);
471
472 if (connp->conn_latch != NULL) {
473 IPLATCH_REFRELE(connp->conn_latch);
474 connp->conn_latch = NULL;
475 }
476 if (connp->conn_latch_in_policy != NULL) {
477 IPPOL_REFRELE(connp->conn_latch_in_policy);
478 connp->conn_latch_in_policy = NULL;
479 }
480 if (connp->conn_latch_in_action != NULL) {
481 IPACT_REFRELE(connp->conn_latch_in_action);
482 connp->conn_latch_in_action = NULL;
483 }
484 if (connp->conn_policy != NULL) {
485 IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
486 connp->conn_policy = NULL;
487 }
488 }
489
490 /*
491 * Cleaup before placing on free list.
492 * Disassociate from the netstack/tcp_stack_t since the freelist
493 * is per squeue and not per netstack.
494 */
495 void
496 tcp_cleanup(tcp_t *tcp)
497 {
498 mblk_t *mp;
499 conn_t *connp = tcp->tcp_connp;
500 tcp_stack_t *tcps = tcp->tcp_tcps;
501 netstack_t *ns = tcps->tcps_netstack;
502 mblk_t *tcp_rsrv_mp;
503
504 tcp_bind_hash_remove(tcp);
505
506 /* Cleanup that which needs the netstack first */
507 tcp_ipsec_cleanup(tcp);
508 ixa_cleanup(connp->conn_ixa);
509
510 if (connp->conn_ht_iphc != NULL) {
511 kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
512 connp->conn_ht_iphc = NULL;
513 connp->conn_ht_iphc_allocated = 0;
514 connp->conn_ht_iphc_len = 0;
515 connp->conn_ht_ulp = NULL;
516 connp->conn_ht_ulp_len = 0;
517 tcp->tcp_ipha = NULL;
518 tcp->tcp_ip6h = NULL;
519 tcp->tcp_tcpha = NULL;
520 }
521
522 /* We clear any IP_OPTIONS and extension headers */
523 ip_pkt_free(&connp->conn_xmit_ipp);
524
525 tcp_free(tcp);
526
527 /*
528 * Since we will bzero the entire structure, we need to
529 * remove it and reinsert it in global hash list. We
530 * know the walkers can't get to this conn because we
531 * had set CONDEMNED flag earlier and checked reference
532 * under conn_lock so walker won't pick it and when we
533 * go the ipcl_globalhash_remove() below, no walker
534 * can get to it.
535 */
536 ipcl_globalhash_remove(connp);
537
538 /* Save some state */
539 mp = tcp->tcp_timercache;
540
541 tcp_rsrv_mp = tcp->tcp_rsrv_mp;
542
543 if (connp->conn_cred != NULL) {
544 crfree(connp->conn_cred);
545 connp->conn_cred = NULL;
546 }
547 ipcl_conn_cleanup(connp);
548 connp->conn_flags = IPCL_TCPCONN;
549
550 /*
551 * Now it is safe to decrement the reference counts.
552 * This might be the last reference on the netstack
553 * in which case it will cause the freeing of the IP Instance.
554 */
555 connp->conn_netstack = NULL;
556 connp->conn_ixa->ixa_ipst = NULL;
557 netstack_rele(ns);
558 ASSERT(tcps != NULL);
559 tcp->tcp_tcps = NULL;
560
561 bzero(tcp, sizeof (tcp_t));
562
563 /* restore the state */
564 tcp->tcp_timercache = mp;
565
566 tcp->tcp_rsrv_mp = tcp_rsrv_mp;
567
568 tcp->tcp_connp = connp;
569
570 ASSERT(connp->conn_tcp == tcp);
571 ASSERT(connp->conn_flags & IPCL_TCPCONN);
572 connp->conn_state_flags = CONN_INCIPIENT;
573 ASSERT(connp->conn_proto == IPPROTO_TCP);
574 ASSERT(connp->conn_ref == 1);
575 }
576
577 /*
578 * Adapt to the information, such as rtt and rtt_sd, provided from the
579 * DCE and IRE maintained by IP.
580 *
581 * Checks for multicast and broadcast destination address.
582 * Returns zero if ok; an errno on failure.
583 *
584 * Note that the MSS calculation here is based on the info given in
585 * the DCE and IRE. We do not do any calculation based on TCP options. They
586 * will be handled in tcp_input_data() when TCP knows which options to use.
587 *
588 * Note on how TCP gets its parameters for a connection.
589 *
590 * When a tcp_t structure is allocated, it gets all the default parameters.
591 * In tcp_set_destination(), it gets those metric parameters, like rtt, rtt_sd,
592 * spipe, rpipe, ... from the route metrics. Route metric overrides the
593 * default.
594 *
595 * An incoming SYN with a multicast or broadcast destination address is dropped
596 * in ip_fanout_v4/v6.
597 *
598 * An incoming SYN with a multicast or broadcast source address is always
599 * dropped in tcp_set_destination, since IPDF_ALLOW_MCBC is not set in
600 * conn_connect.
601 * The same logic in tcp_set_destination also serves to
602 * reject an attempt to connect to a broadcast or multicast (destination)
603 * address.
604 */
605 int
606 tcp_set_destination(tcp_t *tcp)
607 {
608 uint32_t mss_max;
609 uint32_t mss;
610 boolean_t tcp_detached = TCP_IS_DETACHED(tcp);
611 conn_t *connp = tcp->tcp_connp;
612 tcp_stack_t *tcps = tcp->tcp_tcps;
613 iulp_t uinfo;
614 int error;
615 uint32_t flags;
616
617 flags = IPDF_LSO | IPDF_ZCOPY;
618 /*
619 * Make sure we have a dce for the destination to avoid dce_ident
620 * contention for connected sockets.
621 */
622 flags |= IPDF_UNIQUE_DCE;
623
624 if (!tcps->tcps_ignore_path_mtu)
625 connp->conn_ixa->ixa_flags |= IXAF_PMTU_DISCOVERY;
626
627 /* Use conn_lock to satify ASSERT; tcp is already serialized */
628 mutex_enter(&connp->conn_lock);
629 error = conn_connect(connp, &uinfo, flags);
630 mutex_exit(&connp->conn_lock);
631 if (error != 0)
632 return (error);
633
634 error = tcp_build_hdrs(tcp);
635 if (error != 0)
636 return (error);
637
638 tcp->tcp_localnet = uinfo.iulp_localnet;
639
640 if (uinfo.iulp_rtt != 0) {
641 tcp->tcp_rtt_sa = MSEC2NSEC(uinfo.iulp_rtt);
642 tcp->tcp_rtt_sd = MSEC2NSEC(uinfo.iulp_rtt_sd);
643 tcp->tcp_rto = tcp_calculate_rto(tcp, tcps, 0);
644 }
645 if (uinfo.iulp_ssthresh != 0)
646 tcp->tcp_cwnd_ssthresh = uinfo.iulp_ssthresh;
647 else
648 tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
649 if (uinfo.iulp_spipe > 0) {
650 connp->conn_sndbuf = MIN(uinfo.iulp_spipe,
651 tcps->tcps_max_buf);
652 if (tcps->tcps_snd_lowat_fraction != 0) {
653 connp->conn_sndlowat = connp->conn_sndbuf /
654 tcps->tcps_snd_lowat_fraction;
655 }
656 (void) tcp_maxpsz_set(tcp, B_TRUE);
657 }
658 /*
659 * Note that up till now, acceptor always inherits receive
660 * window from the listener. But if there is a metrics
661 * associated with a host, we should use that instead of
662 * inheriting it from listener. Thus we need to pass this
663 * info back to the caller.
664 */
665 if (uinfo.iulp_rpipe > 0) {
666 tcp->tcp_rwnd = MIN(uinfo.iulp_rpipe,
667 tcps->tcps_max_buf);
668 }
669
670 if (uinfo.iulp_rtomax > 0) {
671 tcp->tcp_second_timer_threshold =
672 uinfo.iulp_rtomax;
673 }
674
675 /*
676 * Use the metric option settings, iulp_tstamp_ok and
677 * iulp_wscale_ok, only for active open. What this means
678 * is that if the other side uses timestamp or window
679 * scale option, TCP will also use those options. That
680 * is for passive open. If the application sets a
681 * large window, window scale is enabled regardless of
682 * the value in iulp_wscale_ok. This is the behavior
683 * since 2.6. So we keep it.
684 * The only case left in passive open processing is the
685 * check for SACK.
686 * For ECN, it should probably be like SACK. But the
687 * current value is binary, so we treat it like the other
688 * cases. The metric only controls active open.For passive
689 * open, the ndd param, tcp_ecn_permitted, controls the
690 * behavior.
691 */
692 if (!tcp_detached) {
693 /*
694 * The if check means that the following can only
695 * be turned on by the metrics only IRE, but not off.
696 */
697 if (uinfo.iulp_tstamp_ok)
698 tcp->tcp_snd_ts_ok = B_TRUE;
699 if (uinfo.iulp_wscale_ok)
700 tcp->tcp_snd_ws_ok = B_TRUE;
701 if (uinfo.iulp_sack == 2)
702 tcp->tcp_snd_sack_ok = B_TRUE;
703 if (uinfo.iulp_ecn_ok)
704 tcp->tcp_ecn_ok = B_TRUE;
705 } else {
706 /*
707 * Passive open.
708 *
709 * As above, the if check means that SACK can only be
710 * turned on by the metric only IRE.
711 */
712 if (uinfo.iulp_sack > 0) {
713 tcp->tcp_snd_sack_ok = B_TRUE;
714 }
715 }
716
717 /*
718 * XXX Note that currently, iulp_mtu can be as small as 68
719 * because of PMTUd. So tcp_mss may go to negative if combined
720 * length of all those options exceeds 28 bytes. But because
721 * of the tcp_mss_min check below, we may not have a problem if
722 * tcp_mss_min is of a reasonable value. The default is 1 so
723 * the negative problem still exists. And the check defeats PMTUd.
724 * In fact, if PMTUd finds that the MSS should be smaller than
725 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
726 * value.
727 *
728 * We do not deal with that now. All those problems related to
729 * PMTUd will be fixed later.
730 */
731 ASSERT(uinfo.iulp_mtu != 0);
732 mss = tcp->tcp_initial_pmtu = uinfo.iulp_mtu;
733
734 /* Sanity check for MSS value. */
735 if (connp->conn_ipversion == IPV4_VERSION)
736 mss_max = tcps->tcps_mss_max_ipv4;
737 else
738 mss_max = tcps->tcps_mss_max_ipv6;
739
740 if (tcp->tcp_ipsec_overhead == 0)
741 tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
742
743 mss -= tcp->tcp_ipsec_overhead;
744
745 if (mss < tcps->tcps_mss_min)
746 mss = tcps->tcps_mss_min;
747 if (mss > mss_max)
748 mss = mss_max;
749
750 /* Note that this is the maximum MSS, excluding all options. */
751 tcp->tcp_mss = mss;
752
753 /*
754 * Update the tcp connection with LSO capability.
755 */
756 tcp_update_lso(tcp, connp->conn_ixa);
757
758 /*
759 * Initialize the ISS here now that we have the full connection ID.
760 * The RFC 1948 method of initial sequence number generation requires
761 * knowledge of the full connection ID before setting the ISS.
762 */
763 tcp_iss_init(tcp);
764
765 tcp->tcp_loopback = (uinfo.iulp_loopback | uinfo.iulp_local);
766
767 /*
768 * Make sure that conn is not marked incipient
769 * for incoming connections. A blind
770 * removal of incipient flag is cheaper than
771 * check and removal.
772 */
773 mutex_enter(&connp->conn_lock);
774 connp->conn_state_flags &= ~CONN_INCIPIENT;
775 mutex_exit(&connp->conn_lock);
776 return (0);
777 }
778
779 /*
780 * tcp_clean_death / tcp_close_detached must not be called more than once
781 * on a tcp. Thus every function that potentially calls tcp_clean_death
782 * must check for the tcp state before calling tcp_clean_death.
783 * Eg. tcp_input_data, tcp_eager_kill, tcp_clean_death_wrapper,
784 * tcp_timer_handler, all check for the tcp state.
785 */
786 /* ARGSUSED */
787 void
788 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
789 ip_recv_attr_t *dummy)
790 {
791 tcp_t *tcp = ((conn_t *)arg)->conn_tcp;
792
793 freemsg(mp);
794 if (tcp->tcp_state > TCPS_BOUND)
795 (void) tcp_clean_death(((conn_t *)arg)->conn_tcp, ETIMEDOUT);
796 }
797
798 /*
799 * We are dying for some reason. Try to do it gracefully. (May be called
800 * as writer.)
801 *
802 * Return -1 if the structure was not cleaned up (if the cleanup had to be
803 * done by a service procedure).
804 * TBD - Should the return value distinguish between the tcp_t being
805 * freed and it being reinitialized?
806 */
807 int
808 tcp_clean_death(tcp_t *tcp, int err)
809 {
810 mblk_t *mp;
811 queue_t *q;
812 conn_t *connp = tcp->tcp_connp;
813 tcp_stack_t *tcps = tcp->tcp_tcps;
814
815 if (tcp->tcp_fused)
816 tcp_unfuse(tcp);
817
818 if (tcp->tcp_linger_tid != 0 &&
819 TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
820 tcp_stop_lingering(tcp);
821 }
822
823 ASSERT(tcp != NULL);
824 ASSERT((connp->conn_family == AF_INET &&
825 connp->conn_ipversion == IPV4_VERSION) ||
826 (connp->conn_family == AF_INET6 &&
827 (connp->conn_ipversion == IPV4_VERSION ||
828 connp->conn_ipversion == IPV6_VERSION)));
829
830 if (TCP_IS_DETACHED(tcp)) {
831 if (tcp->tcp_hard_binding) {
832 /*
833 * Its an eager that we are dealing with. We close the
834 * eager but in case a conn_ind has already gone to the
835 * listener, let tcp_accept_finish() send a discon_ind
836 * to the listener and drop the last reference. If the
837 * listener doesn't even know about the eager i.e. the
838 * conn_ind hasn't gone up, blow away the eager and drop
839 * the last reference as well. If the conn_ind has gone
840 * up, state should be BOUND. tcp_accept_finish
841 * will figure out that the connection has received a
842 * RST and will send a DISCON_IND to the application.
843 */
844 tcp_closei_local(tcp);
845 if (!tcp->tcp_tconnind_started) {
846 CONN_DEC_REF(connp);
847 } else {
848 tcp->tcp_state = TCPS_BOUND;
849 DTRACE_TCP6(state__change, void, NULL,
850 ip_xmit_attr_t *, connp->conn_ixa,
851 void, NULL, tcp_t *, tcp, void, NULL,
852 int32_t, TCPS_CLOSED);
853 }
854 } else {
855 tcp_close_detached(tcp);
856 }
857 return (0);
858 }
859
860 TCP_STAT(tcps, tcp_clean_death_nondetached);
861
862 /*
863 * The connection is dead. Decrement listener connection counter if
864 * necessary.
865 */
866 if (tcp->tcp_listen_cnt != NULL)
867 TCP_DECR_LISTEN_CNT(tcp);
868
869 /*
870 * When a connection is moved to TIME_WAIT state, the connection
871 * counter is already decremented. So no need to decrement here
872 * again. See SET_TIME_WAIT() macro.
873 */
874 if (tcp->tcp_state >= TCPS_ESTABLISHED &&
875 tcp->tcp_state < TCPS_TIME_WAIT) {
876 TCPS_CONN_DEC(tcps);
877 }
878
879 q = connp->conn_rq;
880
881 /* Trash all inbound data */
882 if (!IPCL_IS_NONSTR(connp)) {
883 ASSERT(q != NULL);
884 flushq(q, FLUSHALL);
885 }
886
887 /*
888 * If we are at least part way open and there is error
889 * (err==0 implies no error)
890 * notify our client by a T_DISCON_IND.
891 */
892 if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
893 if (tcp->tcp_state >= TCPS_ESTABLISHED &&
894 !TCP_IS_SOCKET(tcp)) {
895 /*
896 * Send M_FLUSH according to TPI. Because sockets will
897 * (and must) ignore FLUSHR we do that only for TPI
898 * endpoints and sockets in STREAMS mode.
899 */
900 (void) putnextctl1(q, M_FLUSH, FLUSHR);
901 }
902 if (connp->conn_debug) {
903 (void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
904 "tcp_clean_death: discon err %d", err);
905 }
906 if (IPCL_IS_NONSTR(connp)) {
907 /* Direct socket, use upcall */
908 (*connp->conn_upcalls->su_disconnected)(
909 connp->conn_upper_handle, tcp->tcp_connid, err);
910 } else {
911 mp = mi_tpi_discon_ind(NULL, err, 0);
912 if (mp != NULL) {
913 putnext(q, mp);
914 } else {
915 if (connp->conn_debug) {
916 (void) strlog(TCP_MOD_ID, 0, 1,
917 SL_ERROR|SL_TRACE,
918 "tcp_clean_death, sending M_ERROR");
919 }
920 (void) putnextctl1(q, M_ERROR, EPROTO);
921 }
922 }
923 if (tcp->tcp_state <= TCPS_SYN_RCVD) {
924 /* SYN_SENT or SYN_RCVD */
925 TCPS_BUMP_MIB(tcps, tcpAttemptFails);
926 } else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
927 /* ESTABLISHED or CLOSE_WAIT */
928 TCPS_BUMP_MIB(tcps, tcpEstabResets);
929 }
930 }
931
932 /*
933 * ESTABLISHED non-STREAMS eagers are not 'detached' because
934 * an upper handle is obtained when the SYN-ACK comes in. So it
935 * should receive the 'disconnected' upcall, but tcp_reinit should
936 * not be called since this is an eager.
937 */
938 if (tcp->tcp_listener != NULL && IPCL_IS_NONSTR(connp)) {
939 tcp_closei_local(tcp);
940 tcp->tcp_state = TCPS_BOUND;
941 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
942 connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
943 int32_t, TCPS_CLOSED);
944 return (0);
945 }
946
947 tcp_reinit(tcp);
948 if (IPCL_IS_NONSTR(connp))
949 (void) tcp_do_unbind(connp);
950
951 return (-1);
952 }
953
954 /*
955 * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
956 * to expire, stop the wait and finish the close.
957 */
958 void
959 tcp_stop_lingering(tcp_t *tcp)
960 {
961 clock_t delta = 0;
962 tcp_stack_t *tcps = tcp->tcp_tcps;
963 conn_t *connp = tcp->tcp_connp;
964
965 tcp->tcp_linger_tid = 0;
966 if (tcp->tcp_state > TCPS_LISTEN) {
967 tcp_acceptor_hash_remove(tcp);
968 mutex_enter(&tcp->tcp_non_sq_lock);
969 if (tcp->tcp_flow_stopped) {
970 tcp_clrqfull(tcp);
971 }
972 mutex_exit(&tcp->tcp_non_sq_lock);
973
974 if (tcp->tcp_timer_tid != 0) {
975 delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
976 tcp->tcp_timer_tid = 0;
977 }
978 /*
979 * Need to cancel those timers which will not be used when
980 * TCP is detached. This has to be done before the conn_wq
981 * is cleared.
982 */
983 tcp_timers_stop(tcp);
984
985 tcp->tcp_detached = B_TRUE;
986 connp->conn_rq = NULL;
987 connp->conn_wq = NULL;
988
989 if (tcp->tcp_state == TCPS_TIME_WAIT) {
990 tcp_time_wait_append(tcp);
991 TCP_DBGSTAT(tcps, tcp_detach_time_wait);
992 goto finish;
993 }
994
995 /*
996 * If delta is zero the timer event wasn't executed and was
997 * successfully canceled. In this case we need to restart it
998 * with the minimal delta possible.
999 */
1000 if (delta >= 0) {
1001 tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
1002 delta ? delta : 1);
1003 }
1004 } else {
1005 tcp_closei_local(tcp);
1006 CONN_DEC_REF(connp);
1007 }
1008 finish:
1009 tcp->tcp_detached = B_TRUE;
1010 connp->conn_rq = NULL;
1011 connp->conn_wq = NULL;
1012
1013 /* Signal closing thread that it can complete close */
1014 mutex_enter(&tcp->tcp_closelock);
1015 tcp->tcp_closed = 1;
1016 cv_signal(&tcp->tcp_closecv);
1017 mutex_exit(&tcp->tcp_closelock);
1018
1019 /* If we have an upper handle (socket), release it */
1020 if (IPCL_IS_NONSTR(connp)) {
1021 ASSERT(connp->conn_upper_handle != NULL);
1022 (*connp->conn_upcalls->su_closed)(connp->conn_upper_handle);
1023 connp->conn_upper_handle = NULL;
1024 connp->conn_upcalls = NULL;
1025 }
1026 }
1027
1028 void
1029 tcp_close_common(conn_t *connp, int flags)
1030 {
1031 tcp_t *tcp = connp->conn_tcp;
1032 mblk_t *mp = &tcp->tcp_closemp;
1033 boolean_t conn_ioctl_cleanup_reqd = B_FALSE;
1034 mblk_t *bp;
1035
1036 ASSERT(connp->conn_ref >= 2);
1037
1038 /*
1039 * Mark the conn as closing. ipsq_pending_mp_add will not
1040 * add any mp to the pending mp list, after this conn has
1041 * started closing.
1042 */
1043 mutex_enter(&connp->conn_lock);
1044 connp->conn_state_flags |= CONN_CLOSING;
1045 if (connp->conn_oper_pending_ill != NULL)
1046 conn_ioctl_cleanup_reqd = B_TRUE;
1047 CONN_INC_REF_LOCKED(connp);
1048 mutex_exit(&connp->conn_lock);
1049 tcp->tcp_closeflags = (uint8_t)flags;
1050 ASSERT(connp->conn_ref >= 3);
1051
1052 /*
1053 * tcp_closemp_used is used below without any protection of a lock
1054 * as we don't expect any one else to use it concurrently at this
1055 * point otherwise it would be a major defect.
1056 */
1057
1058 if (mp->b_prev == NULL)
1059 tcp->tcp_closemp_used = B_TRUE;
1060 else
1061 cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
1062 "connp %p tcp %p\n", (void *)connp, (void *)tcp);
1063
1064 TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1065
1066 /*
1067 * Cleanup any queued ioctls here. This must be done before the wq/rq
1068 * are re-written by tcp_close_output().
1069 */
1070 if (conn_ioctl_cleanup_reqd)
1071 conn_ioctl_cleanup(connp);
1072
1073 /*
1074 * As CONN_CLOSING is set, no further ioctls should be passed down to
1075 * IP for this conn (see the guards in tcp_ioctl, tcp_wput_ioctl and
1076 * tcp_wput_iocdata). If the ioctl was queued on an ipsq,
1077 * conn_ioctl_cleanup should have found it and removed it. If the ioctl
1078 * was still in flight at the time, we wait for it here. See comments
1079 * for CONN_INC_IOCTLREF in ip.h for details.
1080 */
1081 mutex_enter(&connp->conn_lock);
1082 while (connp->conn_ioctlref > 0)
1083 cv_wait(&connp->conn_cv, &connp->conn_lock);
1084 ASSERT(connp->conn_ioctlref == 0);
1085 ASSERT(connp->conn_oper_pending_ill == NULL);
1086 mutex_exit(&connp->conn_lock);
1087
1088 SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
1089 NULL, tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
1090
1091 /*
1092 * For non-STREAMS sockets, the normal case is that the conn makes
1093 * an upcall when it's finally closed, so there is no need to wait
1094 * in the protocol. But in case of SO_LINGER the thread sleeps here
1095 * so it can properly deal with the thread being interrupted.
1096 */
1097 if (IPCL_IS_NONSTR(connp) && connp->conn_linger == 0)
1098 goto nowait;
1099
1100 mutex_enter(&tcp->tcp_closelock);
1101 while (!tcp->tcp_closed) {
1102 if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
1103 /*
1104 * The cv_wait_sig() was interrupted. We now do the
1105 * following:
1106 *
1107 * 1) If the endpoint was lingering, we allow this
1108 * to be interrupted by cancelling the linger timeout
1109 * and closing normally.
1110 *
1111 * 2) Revert to calling cv_wait()
1112 *
1113 * We revert to using cv_wait() to avoid an
1114 * infinite loop which can occur if the calling
1115 * thread is higher priority than the squeue worker
1116 * thread and is bound to the same cpu.
1117 */
1118 if (connp->conn_linger && connp->conn_lingertime > 0) {
1119 mutex_exit(&tcp->tcp_closelock);
1120 /* Entering squeue, bump ref count. */
1121 CONN_INC_REF(connp);
1122 bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
1123 SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
1124 tcp_linger_interrupted, connp, NULL,
1125 tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
1126 mutex_enter(&tcp->tcp_closelock);
1127 }
1128 break;
1129 }
1130 }
1131 while (!tcp->tcp_closed)
1132 cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
1133 mutex_exit(&tcp->tcp_closelock);
1134
1135 /*
1136 * In the case of listener streams that have eagers in the q or q0
1137 * we wait for the eagers to drop their reference to us. conn_rq and
1138 * conn_wq of the eagers point to our queues. By waiting for the
1139 * refcnt to drop to 1, we are sure that the eagers have cleaned
1140 * up their queue pointers and also dropped their references to us.
1141 *
1142 * For non-STREAMS sockets we do not have to wait here; the
1143 * listener will instead make a su_closed upcall when the last
1144 * reference is dropped.
1145 */
1146 if (tcp->tcp_wait_for_eagers && !IPCL_IS_NONSTR(connp)) {
1147 mutex_enter(&connp->conn_lock);
1148 while (connp->conn_ref != 1) {
1149 cv_wait(&connp->conn_cv, &connp->conn_lock);
1150 }
1151 mutex_exit(&connp->conn_lock);
1152 }
1153
1154 nowait:
1155 connp->conn_cpid = NOPID;
1156 }
1157
1158 /*
1159 * Called by tcp_close() routine via squeue when lingering is
1160 * interrupted by a signal.
1161 */
1162
1163 /* ARGSUSED */
1164 static void
1165 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1166 {
1167 conn_t *connp = (conn_t *)arg;
1168 tcp_t *tcp = connp->conn_tcp;
1169
1170 freeb(mp);
1171 if (tcp->tcp_linger_tid != 0 &&
1172 TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
1173 tcp_stop_lingering(tcp);
1174 tcp->tcp_client_errno = EINTR;
1175 }
1176 }
1177
1178 /*
1179 * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
1180 * Some stream heads get upset if they see these later on as anything but NULL.
1181 */
1182 void
1183 tcp_close_mpp(mblk_t **mpp)
1184 {
1185 mblk_t *mp;
1186
1187 if ((mp = *mpp) != NULL) {
1188 do {
1189 mp->b_next = NULL;
1190 mp->b_prev = NULL;
1191 } while ((mp = mp->b_cont) != NULL);
1192
1193 mp = *mpp;
1194 *mpp = NULL;
1195 freemsg(mp);
1196 }
1197 }
1198
1199 /* Do detached close. */
1200 void
1201 tcp_close_detached(tcp_t *tcp)
1202 {
1203 if (tcp->tcp_fused)
1204 tcp_unfuse(tcp);
1205
1206 /*
1207 * Clustering code serializes TCP disconnect callbacks and
1208 * cluster tcp list walks by blocking a TCP disconnect callback
1209 * if a cluster tcp list walk is in progress. This ensures
1210 * accurate accounting of TCPs in the cluster code even though
1211 * the TCP list walk itself is not atomic.
1212 */
1213 tcp_closei_local(tcp);
1214 CONN_DEC_REF(tcp->tcp_connp);
1215 }
1216
1217 /*
1218 * The tcp_t is going away. Remove it from all lists and set it
1219 * to TCPS_CLOSED. The freeing up of memory is deferred until
1220 * tcp_inactive. This is needed since a thread in tcp_rput might have
1221 * done a CONN_INC_REF on this structure before it was removed from the
1222 * hashes.
1223 */
1224 void
1225 tcp_closei_local(tcp_t *tcp)
1226 {
1227 conn_t *connp = tcp->tcp_connp;
1228 tcp_stack_t *tcps = tcp->tcp_tcps;
1229 int32_t oldstate;
1230
1231 if (!TCP_IS_SOCKET(tcp))
1232 tcp_acceptor_hash_remove(tcp);
1233
1234 TCPS_UPDATE_MIB(tcps, tcpHCInSegs, tcp->tcp_ibsegs);
1235 tcp->tcp_ibsegs = 0;
1236 TCPS_UPDATE_MIB(tcps, tcpHCOutSegs, tcp->tcp_obsegs);
1237 tcp->tcp_obsegs = 0;
1238
1239 /*
1240 * This can be called via tcp_time_wait_processing() if TCP gets a
1241 * SYN with sequence number outside the TIME-WAIT connection's
1242 * window. So we need to check for TIME-WAIT state here as the
1243 * connection counter is already decremented. See SET_TIME_WAIT()
1244 * macro
1245 */
1246 if (tcp->tcp_state >= TCPS_ESTABLISHED &&
1247 tcp->tcp_state < TCPS_TIME_WAIT) {
1248 TCPS_CONN_DEC(tcps);
1249 }
1250
1251 /*
1252 * If we are an eager connection hanging off a listener that
1253 * hasn't formally accepted the connection yet, get off its
1254 * list and blow off any data that we have accumulated.
1255 */
1256 if (tcp->tcp_listener != NULL) {
1257 tcp_t *listener = tcp->tcp_listener;
1258 mutex_enter(&listener->tcp_eager_lock);
1259 /*
1260 * tcp_tconnind_started == B_TRUE means that the
1261 * conn_ind has already gone to listener. At
1262 * this point, eager will be closed but we
1263 * leave it in listeners eager list so that
1264 * if listener decides to close without doing
1265 * accept, we can clean this up. In tcp_tli_accept
1266 * we take care of the case of accept on closed
1267 * eager.
1268 */
1269 if (!tcp->tcp_tconnind_started) {
1270 tcp_eager_unlink(tcp);
1271 mutex_exit(&listener->tcp_eager_lock);
1272 /*
1273 * We don't want to have any pointers to the
1274 * listener queue, after we have released our
1275 * reference on the listener
1276 */
1277 ASSERT(tcp->tcp_detached);
1278 connp->conn_rq = NULL;
1279 connp->conn_wq = NULL;
1280 CONN_DEC_REF(listener->tcp_connp);
1281 } else {
1282 mutex_exit(&listener->tcp_eager_lock);
1283 }
1284 }
1285
1286 /* Stop all the timers */
1287 tcp_timers_stop(tcp);
1288
1289 if (tcp->tcp_state == TCPS_LISTEN) {
1290 if (tcp->tcp_ip_addr_cache) {
1291 kmem_free((void *)tcp->tcp_ip_addr_cache,
1292 IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1293 tcp->tcp_ip_addr_cache = NULL;
1294 }
1295 }
1296
1297 /* Decrement listerner connection counter if necessary. */
1298 if (tcp->tcp_listen_cnt != NULL)
1299 TCP_DECR_LISTEN_CNT(tcp);
1300
1301 mutex_enter(&tcp->tcp_non_sq_lock);
1302 if (tcp->tcp_flow_stopped)
1303 tcp_clrqfull(tcp);
1304 mutex_exit(&tcp->tcp_non_sq_lock);
1305
1306 tcp_bind_hash_remove(tcp);
1307 /*
1308 * If the tcp_time_wait_collector (which runs outside the squeue)
1309 * is trying to remove this tcp from the time wait list, we will
1310 * block in tcp_time_wait_remove while trying to acquire the
1311 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
1312 * requires the ipcl_hash_remove to be ordered after the
1313 * tcp_time_wait_remove for the refcnt checks to work correctly.
1314 */
1315 if (tcp->tcp_state == TCPS_TIME_WAIT)
1316 (void) tcp_time_wait_remove(tcp, NULL);
1317 CL_INET_DISCONNECT(connp);
1318 ipcl_hash_remove(connp);
1319 oldstate = tcp->tcp_state;
1320 tcp->tcp_state = TCPS_CLOSED;
1321 /* Need to probe before ixa_cleanup() is called */
1322 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
1323 connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
1324 int32_t, oldstate);
1325 ixa_cleanup(connp->conn_ixa);
1326
1327 /*
1328 * Mark the conn as CONDEMNED
1329 */
1330 mutex_enter(&connp->conn_lock);
1331 connp->conn_state_flags |= CONN_CONDEMNED;
1332 mutex_exit(&connp->conn_lock);
1333
1334 ASSERT(tcp->tcp_time_wait_next == NULL);
1335 ASSERT(tcp->tcp_time_wait_prev == NULL);
1336 ASSERT(tcp->tcp_time_wait_expire == 0);
1337
1338 tcp_ipsec_cleanup(tcp);
1339 }
1340
1341 /*
1342 * tcp is dying (called from ipcl_conn_destroy and error cases).
1343 * Free the tcp_t in either case.
1344 */
1345 void
1346 tcp_free(tcp_t *tcp)
1347 {
1348 mblk_t *mp;
1349 conn_t *connp = tcp->tcp_connp;
1350
1351 ASSERT(tcp != NULL);
1352 ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
1353
1354 connp->conn_rq = NULL;
1355 connp->conn_wq = NULL;
1356
1357 tcp_close_mpp(&tcp->tcp_xmit_head);
1358 tcp_close_mpp(&tcp->tcp_reass_head);
1359 if (tcp->tcp_rcv_list != NULL) {
1360 /* Free b_next chain */
1361 tcp_close_mpp(&tcp->tcp_rcv_list);
1362 }
1363 if ((mp = tcp->tcp_urp_mp) != NULL) {
1364 freemsg(mp);
1365 }
1366 if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
1367 freemsg(mp);
1368 }
1369
1370 if (tcp->tcp_fused_sigurg_mp != NULL) {
1371 ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
1372 freeb(tcp->tcp_fused_sigurg_mp);
1373 tcp->tcp_fused_sigurg_mp = NULL;
1374 }
1375
1376 if (tcp->tcp_ordrel_mp != NULL) {
1377 ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
1378 freeb(tcp->tcp_ordrel_mp);
1379 tcp->tcp_ordrel_mp = NULL;
1380 }
1381
1382 TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
1383 bzero(&tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
1384
1385 if (tcp->tcp_hopopts != NULL) {
1386 mi_free(tcp->tcp_hopopts);
1387 tcp->tcp_hopopts = NULL;
1388 tcp->tcp_hopoptslen = 0;
1389 }
1390 ASSERT(tcp->tcp_hopoptslen == 0);
1391 if (tcp->tcp_dstopts != NULL) {
1392 mi_free(tcp->tcp_dstopts);
1393 tcp->tcp_dstopts = NULL;
1394 tcp->tcp_dstoptslen = 0;
1395 }
1396 ASSERT(tcp->tcp_dstoptslen == 0);
1397 if (tcp->tcp_rthdrdstopts != NULL) {
1398 mi_free(tcp->tcp_rthdrdstopts);
1399 tcp->tcp_rthdrdstopts = NULL;
1400 tcp->tcp_rthdrdstoptslen = 0;
1401 }
1402 ASSERT(tcp->tcp_rthdrdstoptslen == 0);
1403 if (tcp->tcp_rthdr != NULL) {
1404 mi_free(tcp->tcp_rthdr);
1405 tcp->tcp_rthdr = NULL;
1406 tcp->tcp_rthdrlen = 0;
1407 }
1408 ASSERT(tcp->tcp_rthdrlen == 0);
1409
1410 /*
1411 * Following is really a blowing away a union.
1412 * It happens to have exactly two members of identical size
1413 * the following code is enough.
1414 */
1415 tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
1416
1417 /*
1418 * If this is a non-STREAM socket still holding on to an upper
1419 * handle, release it. As a result of fallback we might also see
1420 * STREAMS based conns with upper handles, in which case there is
1421 * nothing to do other than clearing the field.
1422 */
1423 if (connp->conn_upper_handle != NULL) {
1424 if (IPCL_IS_NONSTR(connp)) {
1425 (*connp->conn_upcalls->su_closed)(
1426 connp->conn_upper_handle);
1427 tcp->tcp_detached = B_TRUE;
1428 }
1429 connp->conn_upper_handle = NULL;
1430 connp->conn_upcalls = NULL;
1431 }
1432 }
1433
1434 /*
1435 * tcp_get_conn/tcp_free_conn
1436 *
1437 * tcp_get_conn is used to get a clean tcp connection structure.
1438 * It tries to reuse the connections put on the freelist by the
1439 * time_wait_collector failing which it goes to kmem_cache. This
1440 * way has two benefits compared to just allocating from and
1441 * freeing to kmem_cache.
1442 * 1) The time_wait_collector can free (which includes the cleanup)
1443 * outside the squeue. So when the interrupt comes, we have a clean
1444 * connection sitting in the freelist. Obviously, this buys us
1445 * performance.
1446 *
1447 * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_input_listener
1448 * has multiple disadvantages - tying up the squeue during alloc.
1449 * But allocating the conn/tcp in IP land is also not the best since
1450 * we can't check the 'q' and 'q0' which are protected by squeue and
1451 * blindly allocate memory which might have to be freed here if we are
1452 * not allowed to accept the connection. By using the freelist and
1453 * putting the conn/tcp back in freelist, we don't pay a penalty for
1454 * allocating memory without checking 'q/q0' and freeing it if we can't
1455 * accept the connection.
1456 *
1457 * Care should be taken to put the conn back in the same squeue's freelist
1458 * from which it was allocated. Best results are obtained if conn is
1459 * allocated from listener's squeue and freed to the same. Time wait
1460 * collector will free up the freelist is the connection ends up sitting
1461 * there for too long.
1462 */
1463 void *
1464 tcp_get_conn(void *arg, tcp_stack_t *tcps)
1465 {
1466 tcp_t *tcp = NULL;
1467 conn_t *connp = NULL;
1468 squeue_t *sqp = (squeue_t *)arg;
1469 tcp_squeue_priv_t *tcp_time_wait;
1470 netstack_t *ns;
1471 mblk_t *tcp_rsrv_mp = NULL;
1472
1473 tcp_time_wait =
1474 *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1475
1476 mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1477 tcp = tcp_time_wait->tcp_free_list;
1478 ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
1479 if (tcp != NULL) {
1480 tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1481 tcp_time_wait->tcp_free_list_cnt--;
1482 mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1483 tcp->tcp_time_wait_next = NULL;
1484 connp = tcp->tcp_connp;
1485 connp->conn_flags |= IPCL_REUSED;
1486
1487 ASSERT(tcp->tcp_tcps == NULL);
1488 ASSERT(connp->conn_netstack == NULL);
1489 ASSERT(tcp->tcp_rsrv_mp != NULL);
1490 ns = tcps->tcps_netstack;
1491 netstack_hold(ns);
1492 connp->conn_netstack = ns;
1493 connp->conn_ixa->ixa_ipst = ns->netstack_ip;
1494 tcp->tcp_tcps = tcps;
1495 ipcl_globalhash_insert(connp);
1496
1497 connp->conn_ixa->ixa_notify_cookie = tcp;
1498 ASSERT(connp->conn_ixa->ixa_notify == tcp_notify);
1499 connp->conn_recv = tcp_input_data;
1500 ASSERT(connp->conn_recvicmp == tcp_icmp_input);
1501 ASSERT(connp->conn_verifyicmp == tcp_verifyicmp);
1502 return ((void *)connp);
1503 }
1504 mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1505 /*
1506 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
1507 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
1508 */
1509 tcp_rsrv_mp = allocb(0, BPRI_HI);
1510 if (tcp_rsrv_mp == NULL)
1511 return (NULL);
1512
1513 if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
1514 tcps->tcps_netstack)) == NULL) {
1515 freeb(tcp_rsrv_mp);
1516 return (NULL);
1517 }
1518
1519 tcp = connp->conn_tcp;
1520 tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1521 mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
1522
1523 tcp->tcp_tcps = tcps;
1524
1525 connp->conn_recv = tcp_input_data;
1526 connp->conn_recvicmp = tcp_icmp_input;
1527 connp->conn_verifyicmp = tcp_verifyicmp;
1528
1529 /*
1530 * Register tcp_notify to listen to capability changes detected by IP.
1531 * This upcall is made in the context of the call to conn_ip_output
1532 * thus it is inside the squeue.
1533 */
1534 connp->conn_ixa->ixa_notify = tcp_notify;
1535 connp->conn_ixa->ixa_notify_cookie = tcp;
1536
1537 return ((void *)connp);
1538 }
1539
1540 /*
1541 * Handle connect to IPv4 destinations, including connections for AF_INET6
1542 * sockets connecting to IPv4 mapped IPv6 destinations.
1543 * Returns zero if OK, a positive errno, or a negative TLI error.
1544 */
1545 static int
1546 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
1547 uint_t srcid)
1548 {
1549 ipaddr_t dstaddr = *dstaddrp;
1550 uint16_t lport;
1551 conn_t *connp = tcp->tcp_connp;
1552 tcp_stack_t *tcps = tcp->tcp_tcps;
1553 int error;
1554
1555 ASSERT(connp->conn_ipversion == IPV4_VERSION);
1556
1557 /* Check for attempt to connect to INADDR_ANY */
1558 if (dstaddr == INADDR_ANY) {
1559 /*
1560 * SunOS 4.x and 4.3 BSD allow an application
1561 * to connect a TCP socket to INADDR_ANY.
1562 * When they do this, the kernel picks the
1563 * address of one interface and uses it
1564 * instead. The kernel usually ends up
1565 * picking the address of the loopback
1566 * interface. This is an undocumented feature.
1567 * However, we provide the same thing here
1568 * in order to have source and binary
1569 * compatibility with SunOS 4.x.
1570 * Update the T_CONN_REQ (sin/sin6) since it is used to
1571 * generate the T_CONN_CON.
1572 */
1573 dstaddr = htonl(INADDR_LOOPBACK);
1574 *dstaddrp = dstaddr;
1575 }
1576
1577 /* Handle __sin6_src_id if socket not bound to an IP address */
1578 if (srcid != 0 && connp->conn_laddr_v4 == INADDR_ANY) {
1579 if (!ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
1580 IPCL_ZONEID(connp), B_TRUE, tcps->tcps_netstack)) {
1581 /* Mismatch - conn_laddr_v6 would be v6 address. */
1582 return (EADDRNOTAVAIL);
1583 }
1584 connp->conn_saddr_v6 = connp->conn_laddr_v6;
1585 }
1586
1587 IN6_IPADDR_TO_V4MAPPED(dstaddr, &connp->conn_faddr_v6);
1588 connp->conn_fport = dstport;
1589
1590 /*
1591 * At this point the remote destination address and remote port fields
1592 * in the tcp-four-tuple have been filled in the tcp structure. Now we
1593 * have to see which state tcp was in so we can take appropriate action.
1594 */
1595 if (tcp->tcp_state == TCPS_IDLE) {
1596 /*
1597 * We support a quick connect capability here, allowing
1598 * clients to transition directly from IDLE to SYN_SENT
1599 * tcp_bindi will pick an unused port, insert the connection
1600 * in the bind hash and transition to BOUND state.
1601 */
1602 lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
1603 tcp, B_TRUE);
1604 lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
1605 B_FALSE, B_FALSE);
1606 if (lport == 0)
1607 return (-TNOADDR);
1608 }
1609
1610 /*
1611 * Lookup the route to determine a source address and the uinfo.
1612 * Setup TCP parameters based on the metrics/DCE.
1613 */
1614 error = tcp_set_destination(tcp);
1615 if (error != 0)
1616 return (error);
1617
1618 /*
1619 * Don't let an endpoint connect to itself.
1620 */
1621 if (connp->conn_faddr_v4 == connp->conn_laddr_v4 &&
1622 connp->conn_fport == connp->conn_lport)
1623 return (-TBADADDR);
1624
1625 tcp->tcp_state = TCPS_SYN_SENT;
1626
1627 return (ipcl_conn_insert_v4(connp));
1628 }
1629
1630 /*
1631 * Handle connect to IPv6 destinations.
1632 * Returns zero if OK, a positive errno, or a negative TLI error.
1633 */
1634 static int
1635 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
1636 uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
1637 {
1638 uint16_t lport;
1639 conn_t *connp = tcp->tcp_connp;
1640 tcp_stack_t *tcps = tcp->tcp_tcps;
1641 int error;
1642
1643 ASSERT(connp->conn_family == AF_INET6);
1644
1645 /*
1646 * If we're here, it means that the destination address is a native
1647 * IPv6 address. Return an error if conn_ipversion is not IPv6. A
1648 * reason why it might not be IPv6 is if the socket was bound to an
1649 * IPv4-mapped IPv6 address.
1650 */
1651 if (connp->conn_ipversion != IPV6_VERSION)
1652 return (-TBADADDR);
1653
1654 /*
1655 * Interpret a zero destination to mean loopback.
1656 * Update the T_CONN_REQ (sin/sin6) since it is used to
1657 * generate the T_CONN_CON.
1658 */
1659 if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp))
1660 *dstaddrp = ipv6_loopback;
1661
1662 /* Handle __sin6_src_id if socket not bound to an IP address */
1663 if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6)) {
1664 if (!ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
1665 IPCL_ZONEID(connp), B_FALSE, tcps->tcps_netstack)) {
1666 /* Mismatch - conn_laddr_v6 would be v4-mapped. */
1667 return (EADDRNOTAVAIL);
1668 }
1669 connp->conn_saddr_v6 = connp->conn_laddr_v6;
1670 }
1671
1672 /*
1673 * Take care of the scope_id now.
1674 */
1675 if (scope_id != 0 && IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
1676 connp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
1677 connp->conn_ixa->ixa_scopeid = scope_id;
1678 } else {
1679 connp->conn_ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
1680 }
1681
1682 connp->conn_flowinfo = flowinfo;
1683 connp->conn_faddr_v6 = *dstaddrp;
1684 connp->conn_fport = dstport;
1685
1686 /*
1687 * At this point the remote destination address and remote port fields
1688 * in the tcp-four-tuple have been filled in the tcp structure. Now we
1689 * have to see which state tcp was in so we can take appropriate action.
1690 */
1691 if (tcp->tcp_state == TCPS_IDLE) {
1692 /*
1693 * We support a quick connect capability here, allowing
1694 * clients to transition directly from IDLE to SYN_SENT
1695 * tcp_bindi will pick an unused port, insert the connection
1696 * in the bind hash and transition to BOUND state.
1697 */
1698 lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
1699 tcp, B_TRUE);
1700 lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
1701 B_FALSE, B_FALSE);
1702 if (lport == 0)
1703 return (-TNOADDR);
1704 }
1705
1706 /*
1707 * Lookup the route to determine a source address and the uinfo.
1708 * Setup TCP parameters based on the metrics/DCE.
1709 */
1710 error = tcp_set_destination(tcp);
1711 if (error != 0)
1712 return (error);
1713
1714 /*
1715 * Don't let an endpoint connect to itself.
1716 */
1717 if (IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6, &connp->conn_laddr_v6) &&
1718 connp->conn_fport == connp->conn_lport)
1719 return (-TBADADDR);
1720
1721 tcp->tcp_state = TCPS_SYN_SENT;
1722
1723 return (ipcl_conn_insert_v6(connp));
1724 }
1725
1726 /*
1727 * Disconnect
1728 * Note that unlike other functions this returns a positive tli error
1729 * when it fails; it never returns an errno.
1730 */
1731 static int
1732 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
1733 {
1734 conn_t *lconnp;
1735 tcp_stack_t *tcps = tcp->tcp_tcps;
1736 conn_t *connp = tcp->tcp_connp;
1737
1738 /*
1739 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
1740 * when the stream is in BOUND state. Do not send a reset,
1741 * since the destination IP address is not valid, and it can
1742 * be the initialized value of all zeros (broadcast address).
1743 */
1744 if (tcp->tcp_state <= TCPS_BOUND) {
1745 if (connp->conn_debug) {
1746 (void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
1747 "tcp_disconnect: bad state, %d", tcp->tcp_state);
1748 }
1749 return (TOUTSTATE);
1750 } else if (tcp->tcp_state >= TCPS_ESTABLISHED) {
1751 TCPS_CONN_DEC(tcps);
1752 }
1753
1754 if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
1755
1756 /*
1757 * According to TPI, for non-listeners, ignore seqnum
1758 * and disconnect.
1759 * Following interpretation of -1 seqnum is historical
1760 * and implied TPI ? (TPI only states that for T_CONN_IND,
1761 * a valid seqnum should not be -1).
1762 *
1763 * -1 means disconnect everything
1764 * regardless even on a listener.
1765 */
1766
1767 int old_state = tcp->tcp_state;
1768 ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
1769
1770 /*
1771 * The connection can't be on the tcp_time_wait_head list
1772 * since it is not detached.
1773 */
1774 ASSERT(tcp->tcp_time_wait_next == NULL);
1775 ASSERT(tcp->tcp_time_wait_prev == NULL);
1776 ASSERT(tcp->tcp_time_wait_expire == 0);
1777 /*
1778 * If it used to be a listener, check to make sure no one else
1779 * has taken the port before switching back to LISTEN state.
1780 */
1781 if (connp->conn_ipversion == IPV4_VERSION) {
1782 lconnp = ipcl_lookup_listener_v4(connp->conn_lport,
1783 connp->conn_laddr_v4, IPCL_ZONEID(connp), ipst);
1784 } else {
1785 uint_t ifindex = 0;
1786
1787 if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)
1788 ifindex = connp->conn_ixa->ixa_scopeid;
1789
1790 /* Allow conn_bound_if listeners? */
1791 lconnp = ipcl_lookup_listener_v6(connp->conn_lport,
1792 &connp->conn_laddr_v6, ifindex, IPCL_ZONEID(connp),
1793 ipst);
1794 }
1795 if (tcp->tcp_conn_req_max && lconnp == NULL) {
1796 tcp->tcp_state = TCPS_LISTEN;
1797 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
1798 connp->conn_ixa, void, NULL, tcp_t *, tcp, void,
1799 NULL, int32_t, old_state);
1800 } else if (old_state > TCPS_BOUND) {
1801 tcp->tcp_conn_req_max = 0;
1802 tcp->tcp_state = TCPS_BOUND;
1803 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
1804 connp->conn_ixa, void, NULL, tcp_t *, tcp, void,
1805 NULL, int32_t, old_state);
1806
1807 /*
1808 * If this end point is not going to become a listener,
1809 * decrement the listener connection count if
1810 * necessary. Note that we do not do this if it is
1811 * going to be a listner (the above if case) since
1812 * then it may remove the counter struct.
1813 */
1814 if (tcp->tcp_listen_cnt != NULL)
1815 TCP_DECR_LISTEN_CNT(tcp);
1816 }
1817 if (lconnp != NULL)
1818 CONN_DEC_REF(lconnp);
1819 switch (old_state) {
1820 case TCPS_SYN_SENT:
1821 case TCPS_SYN_RCVD:
1822 TCPS_BUMP_MIB(tcps, tcpAttemptFails);
1823 break;
1824 case TCPS_ESTABLISHED:
1825 case TCPS_CLOSE_WAIT:
1826 TCPS_BUMP_MIB(tcps, tcpEstabResets);
1827 break;
1828 }
1829
1830 if (tcp->tcp_fused)
1831 tcp_unfuse(tcp);
1832
1833 mutex_enter(&tcp->tcp_eager_lock);
1834 if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
1835 (tcp->tcp_conn_req_cnt_q != 0)) {
1836 tcp_eager_cleanup(tcp, 0);
1837 }
1838 mutex_exit(&tcp->tcp_eager_lock);
1839
1840 tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
1841 tcp->tcp_rnxt, TH_RST | TH_ACK);
1842
1843 tcp_reinit(tcp);
1844
1845 return (0);
1846 } else if (!tcp_eager_blowoff(tcp, seqnum)) {
1847 return (TBADSEQ);
1848 }
1849 return (0);
1850 }
1851
1852 /*
1853 * Our client hereby directs us to reject the connection request
1854 * that tcp_input_listener() marked with 'seqnum'. Rejection consists
1855 * of sending the appropriate RST, not an ICMP error.
1856 */
1857 void
1858 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
1859 {
1860 t_scalar_t seqnum;
1861 int error;
1862 conn_t *connp = tcp->tcp_connp;
1863
1864 ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
1865 if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
1866 tcp_err_ack(tcp, mp, TPROTO, 0);
1867 return;
1868 }
1869 seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
1870 error = tcp_disconnect_common(tcp, seqnum);
1871 if (error != 0)
1872 tcp_err_ack(tcp, mp, error, 0);
1873 else {
1874 if (tcp->tcp_state >= TCPS_ESTABLISHED) {
1875 /* Send M_FLUSH according to TPI */
1876 (void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
1877 }
1878 mp = mi_tpi_ok_ack_alloc(mp);
1879 if (mp != NULL)
1880 putnext(connp->conn_rq, mp);
1881 }
1882 }
1883
1884 /*
1885 * Handle reinitialization of a tcp structure.
1886 * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
1887 */
1888 static void
1889 tcp_reinit(tcp_t *tcp)
1890 {
1891 mblk_t *mp;
1892 tcp_stack_t *tcps = tcp->tcp_tcps;
1893 conn_t *connp = tcp->tcp_connp;
1894 int32_t oldstate;
1895
1896 /* tcp_reinit should never be called for detached tcp_t's */
1897 ASSERT(tcp->tcp_listener == NULL);
1898 ASSERT((connp->conn_family == AF_INET &&
1899 connp->conn_ipversion == IPV4_VERSION) ||
1900 (connp->conn_family == AF_INET6 &&
1901 (connp->conn_ipversion == IPV4_VERSION ||
1902 connp->conn_ipversion == IPV6_VERSION)));
1903
1904 /* Cancel outstanding timers */
1905 tcp_timers_stop(tcp);
1906
1907 /*
1908 * Reset everything in the state vector, after updating global
1909 * MIB data from instance counters.
1910 */
1911 TCPS_UPDATE_MIB(tcps, tcpHCInSegs, tcp->tcp_ibsegs);
1912 tcp->tcp_ibsegs = 0;
1913 TCPS_UPDATE_MIB(tcps, tcpHCOutSegs, tcp->tcp_obsegs);
1914 tcp->tcp_obsegs = 0;
1915
1916 tcp_close_mpp(&tcp->tcp_xmit_head);
1917 if (tcp->tcp_snd_zcopy_aware)
1918 tcp_zcopy_notify(tcp);
1919 tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
1920 tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
1921 mutex_enter(&tcp->tcp_non_sq_lock);
1922 if (tcp->tcp_flow_stopped &&
1923 TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
1924 tcp_clrqfull(tcp);
1925 }
1926 mutex_exit(&tcp->tcp_non_sq_lock);
1927 tcp_close_mpp(&tcp->tcp_reass_head);
1928 tcp->tcp_reass_tail = NULL;
1929 if (tcp->tcp_rcv_list != NULL) {
1930 /* Free b_next chain */
1931 tcp_close_mpp(&tcp->tcp_rcv_list);
1932 tcp->tcp_rcv_last_head = NULL;
1933 tcp->tcp_rcv_last_tail = NULL;
1934 tcp->tcp_rcv_cnt = 0;
1935 }
1936 tcp->tcp_rcv_last_tail = NULL;
1937
1938 if ((mp = tcp->tcp_urp_mp) != NULL) {
1939 freemsg(mp);
1940 tcp->tcp_urp_mp = NULL;
1941 }
1942 if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
1943 freemsg(mp);
1944 tcp->tcp_urp_mark_mp = NULL;
1945 }
1946 if (tcp->tcp_fused_sigurg_mp != NULL) {
1947 ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
1948 freeb(tcp->tcp_fused_sigurg_mp);
1949 tcp->tcp_fused_sigurg_mp = NULL;
1950 }
1951 if (tcp->tcp_ordrel_mp != NULL) {
1952 ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
1953 freeb(tcp->tcp_ordrel_mp);
1954 tcp->tcp_ordrel_mp = NULL;
1955 }
1956
1957 /*
1958 * Following is a union with two members which are
1959 * identical types and size so the following cleanup
1960 * is enough.
1961 */
1962 tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
1963
1964 CL_INET_DISCONNECT(connp);
1965
1966 /*
1967 * The connection can't be on the tcp_time_wait_head list
1968 * since it is not detached.
1969 */
1970 ASSERT(tcp->tcp_time_wait_next == NULL);
1971 ASSERT(tcp->tcp_time_wait_prev == NULL);
1972 ASSERT(tcp->tcp_time_wait_expire == 0);
1973
1974 /*
1975 * Reset/preserve other values
1976 */
1977 tcp_reinit_values(tcp);
1978 ipcl_hash_remove(connp);
1979 /* Note that ixa_cred gets cleared in ixa_cleanup */
1980 ixa_cleanup(connp->conn_ixa);
1981 tcp_ipsec_cleanup(tcp);
1982
1983 connp->conn_laddr_v6 = connp->conn_bound_addr_v6;
1984 connp->conn_saddr_v6 = connp->conn_bound_addr_v6;
1985 oldstate = tcp->tcp_state;
1986
1987 if (tcp->tcp_conn_req_max != 0) {
1988 /*
1989 * This is the case when a TLI program uses the same
1990 * transport end point to accept a connection. This
1991 * makes the TCP both a listener and acceptor. When
1992 * this connection is closed, we need to set the state
1993 * back to TCPS_LISTEN. Make sure that the eager list
1994 * is reinitialized.
1995 *
1996 * Note that this stream is still bound to the four
1997 * tuples of the previous connection in IP. If a new
1998 * SYN with different foreign address comes in, IP will
1999 * not find it and will send it to the global queue. In
2000 * the global queue, TCP will do a tcp_lookup_listener()
2001 * to find this stream. This works because this stream
2002 * is only removed from connected hash.
2003 *
2004 */
2005 tcp->tcp_state = TCPS_LISTEN;
2006 tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
2007 tcp->tcp_eager_next_drop_q0 = tcp;
2008 tcp->tcp_eager_prev_drop_q0 = tcp;
2009 /*
2010 * Initially set conn_recv to tcp_input_listener_unbound to try
2011 * to pick a good squeue for the listener when the first SYN
2012 * arrives. tcp_input_listener_unbound sets it to
2013 * tcp_input_listener on that first SYN.
2014 */
2015 connp->conn_recv = tcp_input_listener_unbound;
2016
2017 connp->conn_proto = IPPROTO_TCP;
2018 connp->conn_faddr_v6 = ipv6_all_zeros;
2019 connp->conn_fport = 0;
2020
2021 (void) ipcl_bind_insert(connp);
2022 } else {
2023 tcp->tcp_state = TCPS_BOUND;
2024 }
2025
2026 /*
2027 * Initialize to default values
2028 */
2029 tcp_init_values(tcp, NULL);
2030
2031 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
2032 connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
2033 int32_t, oldstate);
2034
2035 ASSERT(tcp->tcp_ptpbhn != NULL);
2036 tcp->tcp_rwnd = connp->conn_rcvbuf;
2037 tcp->tcp_mss = connp->conn_ipversion != IPV4_VERSION ?
2038 tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
2039 }
2040
2041 /*
2042 * Force values to zero that need be zero.
2043 * Do not touch values asociated with the BOUND or LISTEN state
2044 * since the connection will end up in that state after the reinit.
2045 * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
2046 * structure!
2047 */
2048 static void
2049 tcp_reinit_values(tcp_t *tcp)
2050 {
2051 tcp_stack_t *tcps = tcp->tcp_tcps;
2052 conn_t *connp = tcp->tcp_connp;
2053
2054 #ifndef lint
2055 #define DONTCARE(x)
2056 #define PRESERVE(x)
2057 #else
2058 #define DONTCARE(x) ((x) = (x))
2059 #define PRESERVE(x) ((x) = (x))
2060 #endif /* lint */
2061
2062 PRESERVE(tcp->tcp_bind_hash_port);
2063 PRESERVE(tcp->tcp_bind_hash);
2064 PRESERVE(tcp->tcp_ptpbhn);
2065 PRESERVE(tcp->tcp_acceptor_hash);
2066 PRESERVE(tcp->tcp_ptpahn);
2067
2068 /* Should be ASSERT NULL on these with new code! */
2069 ASSERT(tcp->tcp_time_wait_next == NULL);
2070 ASSERT(tcp->tcp_time_wait_prev == NULL);
2071 ASSERT(tcp->tcp_time_wait_expire == 0);
2072 PRESERVE(tcp->tcp_state);
2073 PRESERVE(connp->conn_rq);
2074 PRESERVE(connp->conn_wq);
2075
2076 ASSERT(tcp->tcp_xmit_head == NULL);
2077 ASSERT(tcp->tcp_xmit_last == NULL);
2078 ASSERT(tcp->tcp_unsent == 0);
2079 ASSERT(tcp->tcp_xmit_tail == NULL);
2080 ASSERT(tcp->tcp_xmit_tail_unsent == 0);
2081
2082 tcp->tcp_snxt = 0; /* Displayed in mib */
2083 tcp->tcp_suna = 0; /* Displayed in mib */
2084 tcp->tcp_swnd = 0;
2085 DONTCARE(tcp->tcp_cwnd); /* Init in tcp_process_options */
2086
2087 ASSERT(tcp->tcp_ibsegs == 0);
2088 ASSERT(tcp->tcp_obsegs == 0);
2089
2090 if (connp->conn_ht_iphc != NULL) {
2091 kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
2092 connp->conn_ht_iphc = NULL;
2093 connp->conn_ht_iphc_allocated = 0;
2094 connp->conn_ht_iphc_len = 0;
2095 connp->conn_ht_ulp = NULL;
2096 connp->conn_ht_ulp_len = 0;
2097 tcp->tcp_ipha = NULL;
2098 tcp->tcp_ip6h = NULL;
2099 tcp->tcp_tcpha = NULL;
2100 }
2101
2102 /* We clear any IP_OPTIONS and extension headers */
2103 ip_pkt_free(&connp->conn_xmit_ipp);
2104
2105 DONTCARE(tcp->tcp_naglim); /* Init in tcp_init_values */
2106 DONTCARE(tcp->tcp_ipha);
2107 DONTCARE(tcp->tcp_ip6h);
2108 DONTCARE(tcp->tcp_tcpha);
2109 tcp->tcp_valid_bits = 0;
2110
2111 DONTCARE(tcp->tcp_timer_backoff); /* Init in tcp_init_values */
2112 DONTCARE(tcp->tcp_last_recv_time); /* Init in tcp_init_values */
2113 tcp->tcp_last_rcv_lbolt = 0;
2114
2115 tcp->tcp_init_cwnd = 0;
2116
2117 tcp->tcp_urp_last_valid = 0;
2118 tcp->tcp_hard_binding = 0;
2119
2120 tcp->tcp_fin_acked = 0;
2121 tcp->tcp_fin_rcvd = 0;
2122 tcp->tcp_fin_sent = 0;
2123 tcp->tcp_ordrel_done = 0;
2124
2125 tcp->tcp_detached = 0;
2126
2127 tcp->tcp_snd_ws_ok = B_FALSE;
2128 tcp->tcp_snd_ts_ok = B_FALSE;
2129 tcp->tcp_zero_win_probe = 0;
2130
2131 tcp->tcp_loopback = 0;
2132 tcp->tcp_localnet = 0;
2133 tcp->tcp_syn_defense = 0;
2134 tcp->tcp_set_timer = 0;
2135
2136 tcp->tcp_active_open = 0;
2137 tcp->tcp_rexmit = B_FALSE;
2138 tcp->tcp_xmit_zc_clean = B_FALSE;
2139
2140 tcp->tcp_snd_sack_ok = B_FALSE;
2141 tcp->tcp_hwcksum = B_FALSE;
2142
2143 DONTCARE(tcp->tcp_maxpsz_multiplier); /* Init in tcp_init_values */
2144
2145 tcp->tcp_conn_def_q0 = 0;
2146 tcp->tcp_ip_forward_progress = B_FALSE;
2147 tcp->tcp_ecn_ok = B_FALSE;
2148
2149 tcp->tcp_cwr = B_FALSE;
2150 tcp->tcp_ecn_echo_on = B_FALSE;
2151 tcp->tcp_is_wnd_shrnk = B_FALSE;
2152
2153 TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
2154 bzero(&tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
2155
2156 tcp->tcp_rcv_ws = 0;
2157 tcp->tcp_snd_ws = 0;
2158 tcp->tcp_ts_recent = 0;
2159 tcp->tcp_rnxt = 0; /* Displayed in mib */
2160 DONTCARE(tcp->tcp_rwnd); /* Set in tcp_reinit() */
2161 tcp->tcp_initial_pmtu = 0;
2162
2163 ASSERT(tcp->tcp_reass_head == NULL);
2164 ASSERT(tcp->tcp_reass_tail == NULL);
2165
2166 tcp->tcp_cwnd_cnt = 0;
2167
2168 ASSERT(tcp->tcp_rcv_list == NULL);
2169 ASSERT(tcp->tcp_rcv_last_head == NULL);
2170 ASSERT(tcp->tcp_rcv_last_tail == NULL);
2171 ASSERT(tcp->tcp_rcv_cnt == 0);
2172
2173 DONTCARE(tcp->tcp_cwnd_ssthresh); /* Init in tcp_set_destination */
2174 DONTCARE(tcp->tcp_cwnd_max); /* Init in tcp_init_values */
2175 tcp->tcp_csuna = 0;
2176
2177 tcp->tcp_rto = 0; /* Displayed in MIB */
2178 DONTCARE(tcp->tcp_rtt_sa); /* Init in tcp_init_values */
2179 DONTCARE(tcp->tcp_rtt_sd); /* Init in tcp_init_values */
2180 tcp->tcp_rtt_update = 0;
2181
2182 DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
2183 DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
2184
2185 tcp->tcp_rack = 0; /* Displayed in mib */
2186 tcp->tcp_rack_cnt = 0;
2187 tcp->tcp_rack_cur_max = 0;
2188 tcp->tcp_rack_abs_max = 0;
2189
2190 tcp->tcp_max_swnd = 0;
2191
2192 ASSERT(tcp->tcp_listener == NULL);
2193
2194 DONTCARE(tcp->tcp_irs); /* tcp_valid_bits cleared */
2195 DONTCARE(tcp->tcp_iss); /* tcp_valid_bits cleared */
2196 DONTCARE(tcp->tcp_fss); /* tcp_valid_bits cleared */
2197 DONTCARE(tcp->tcp_urg); /* tcp_valid_bits cleared */
2198
2199 ASSERT(tcp->tcp_conn_req_cnt_q == 0);
2200 ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
2201 PRESERVE(tcp->tcp_conn_req_max);
2202 PRESERVE(tcp->tcp_conn_req_seqnum);
2203
2204 DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
2205 DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
2206 DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
2207 DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
2208
2209 DONTCARE(tcp->tcp_urp_last); /* tcp_urp_last_valid is cleared */
2210 ASSERT(tcp->tcp_urp_mp == NULL);
2211 ASSERT(tcp->tcp_urp_mark_mp == NULL);
2212 ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
2213
2214 ASSERT(tcp->tcp_eager_next_q == NULL);
2215 ASSERT(tcp->tcp_eager_last_q == NULL);
2216 ASSERT((tcp->tcp_eager_next_q0 == NULL &&
2217 tcp->tcp_eager_prev_q0 == NULL) ||
2218 tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
2219 ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
2220
2221 ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
2222 tcp->tcp_eager_prev_drop_q0 == NULL) ||
2223 tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
2224
2225 DONTCARE(tcp->tcp_ka_rinterval); /* Init in tcp_init_values */
2226 DONTCARE(tcp->tcp_ka_abort_thres); /* Init in tcp_init_values */
2227 DONTCARE(tcp->tcp_ka_cnt); /* Init in tcp_init_values */
2228
2229 tcp->tcp_client_errno = 0;
2230
2231 DONTCARE(connp->conn_sum); /* Init in tcp_init_values */
2232
2233 connp->conn_faddr_v6 = ipv6_all_zeros; /* Displayed in MIB */
2234
2235 PRESERVE(connp->conn_bound_addr_v6);
2236 tcp->tcp_last_sent_len = 0;
2237 tcp->tcp_dupack_cnt = 0;
2238
2239 connp->conn_fport = 0; /* Displayed in MIB */
2240 PRESERVE(connp->conn_lport);
2241
2242 PRESERVE(tcp->tcp_acceptor_lockp);
2243
2244 ASSERT(tcp->tcp_ordrel_mp == NULL);
2245 PRESERVE(tcp->tcp_acceptor_id);
2246 DONTCARE(tcp->tcp_ipsec_overhead);
2247
2248 PRESERVE(connp->conn_family);
2249 /* Remove any remnants of mapped address binding */
2250 if (connp->conn_family == AF_INET6) {
2251 connp->conn_ipversion = IPV6_VERSION;
2252 tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
2253 } else {
2254 connp->conn_ipversion = IPV4_VERSION;
2255 tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
2256 }
2257
2258 connp->conn_bound_if = 0;
2259 connp->conn_recv_ancillary.crb_all = 0;
2260 tcp->tcp_recvifindex = 0;
2261 tcp->tcp_recvhops = 0;
2262 tcp->tcp_closed = 0;
2263 if (tcp->tcp_hopopts != NULL) {
2264 mi_free(tcp->tcp_hopopts);
2265 tcp->tcp_hopopts = NULL;
2266 tcp->tcp_hopoptslen = 0;
2267 }
2268 ASSERT(tcp->tcp_hopoptslen == 0);
2269 if (tcp->tcp_dstopts != NULL) {
2270 mi_free(tcp->tcp_dstopts);
2271 tcp->tcp_dstopts = NULL;
2272 tcp->tcp_dstoptslen = 0;
2273 }
2274 ASSERT(tcp->tcp_dstoptslen == 0);
2275 if (tcp->tcp_rthdrdstopts != NULL) {
2276 mi_free(tcp->tcp_rthdrdstopts);
2277 tcp->tcp_rthdrdstopts = NULL;
2278 tcp->tcp_rthdrdstoptslen = 0;
2279 }
2280 ASSERT(tcp->tcp_rthdrdstoptslen == 0);
2281 if (tcp->tcp_rthdr != NULL) {
2282 mi_free(tcp->tcp_rthdr);
2283 tcp->tcp_rthdr = NULL;
2284 tcp->tcp_rthdrlen = 0;
2285 }
2286 ASSERT(tcp->tcp_rthdrlen == 0);
2287
2288 /* Reset fusion-related fields */
2289 tcp->tcp_fused = B_FALSE;
2290 tcp->tcp_unfusable = B_FALSE;
2291 tcp->tcp_fused_sigurg = B_FALSE;
2292 tcp->tcp_loopback_peer = NULL;
2293
2294 tcp->tcp_lso = B_FALSE;
2295
2296 tcp->tcp_in_ack_unsent = 0;
2297 tcp->tcp_cork = B_FALSE;
2298 tcp->tcp_tconnind_started = B_FALSE;
2299
2300 PRESERVE(tcp->tcp_squeue_bytes);
2301
2302 tcp->tcp_closemp_used = B_FALSE;
2303
2304 PRESERVE(tcp->tcp_rsrv_mp);
2305 PRESERVE(tcp->tcp_rsrv_mp_lock);
2306
2307 #ifdef DEBUG
2308 DONTCARE(tcp->tcmp_stk[0]);
2309 #endif
2310
2311 PRESERVE(tcp->tcp_connid);
2312
2313 ASSERT(tcp->tcp_listen_cnt == NULL);
2314 ASSERT(tcp->tcp_reass_tid == 0);
2315
2316 #undef DONTCARE
2317 #undef PRESERVE
2318 }
2319
2320 /*
2321 * Initialize the various fields in tcp_t. If parent (the listener) is non
2322 * NULL, certain values will be inheritted from it.
2323 */
2324 void
2325 tcp_init_values(tcp_t *tcp, tcp_t *parent)
2326 {
2327 tcp_stack_t *tcps = tcp->tcp_tcps;
2328 conn_t *connp = tcp->tcp_connp;
2329
2330 ASSERT((connp->conn_family == AF_INET &&
2331 connp->conn_ipversion == IPV4_VERSION) ||
2332 (connp->conn_family == AF_INET6 &&
2333 (connp->conn_ipversion == IPV4_VERSION ||
2334 connp->conn_ipversion == IPV6_VERSION)));
2335
2336 if (parent == NULL) {
2337 tcp->tcp_naglim = tcps->tcps_naglim_def;
2338
2339 tcp->tcp_rto_initial = tcps->tcps_rexmit_interval_initial;
2340 tcp->tcp_rto_min = tcps->tcps_rexmit_interval_min;
2341 tcp->tcp_rto_max = tcps->tcps_rexmit_interval_max;
2342
2343 tcp->tcp_first_ctimer_threshold =
2344 tcps->tcps_ip_notify_cinterval;
2345 tcp->tcp_second_ctimer_threshold =
2346 tcps->tcps_ip_abort_cinterval;
2347 tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
2348 tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
2349
2350 tcp->tcp_fin_wait_2_flush_interval =
2351 tcps->tcps_fin_wait_2_flush_interval;
2352
2353 tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
2354 tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
2355 tcp->tcp_ka_cnt = 0;
2356 tcp->tcp_ka_rinterval = 0;
2357
2358 /*
2359 * Default value of tcp_init_cwnd is 0, so no need to set here
2360 * if parent is NULL. But we need to inherit it from parent.
2361 */
2362 } else {
2363 /* Inherit various TCP parameters from the parent. */
2364 tcp->tcp_naglim = parent->tcp_naglim;
2365
2366 tcp->tcp_rto_initial = parent->tcp_rto_initial;
2367 tcp->tcp_rto_min = parent->tcp_rto_min;
2368 tcp->tcp_rto_max = parent->tcp_rto_max;
2369
2370 tcp->tcp_first_ctimer_threshold =
2371 parent->tcp_first_ctimer_threshold;
2372 tcp->tcp_second_ctimer_threshold =
2373 parent->tcp_second_ctimer_threshold;
2374 tcp->tcp_first_timer_threshold =
2375 parent->tcp_first_timer_threshold;
2376 tcp->tcp_second_timer_threshold =
2377 parent->tcp_second_timer_threshold;
2378
2379 tcp->tcp_fin_wait_2_flush_interval =
2380 parent->tcp_fin_wait_2_flush_interval;
2381
2382 tcp->tcp_ka_interval = parent->tcp_ka_interval;
2383 tcp->tcp_ka_abort_thres = parent->tcp_ka_abort_thres;
2384 tcp->tcp_ka_cnt = parent->tcp_ka_cnt;
2385 tcp->tcp_ka_rinterval = parent->tcp_ka_rinterval;
2386
2387 tcp->tcp_init_cwnd = parent->tcp_init_cwnd;
2388 }
2389
2390 /*
2391 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
2392 * will be close to tcp_rexmit_interval_initial. By doing this, we
2393 * allow the algorithm to adjust slowly to large fluctuations of RTT
2394 * during first few transmissions of a connection as seen in slow
2395 * links.
2396 */
2397 tcp->tcp_rtt_sa = MSEC2NSEC(tcp->tcp_rto_initial) << 2;
2398 tcp->tcp_rtt_sd = MSEC2NSEC(tcp->tcp_rto_initial) >> 1;
2399 tcp->tcp_rto = tcp_calculate_rto(tcp, tcps,
2400 tcps->tcps_conn_grace_period);
2401
2402 tcp->tcp_timer_backoff = 0;
2403 tcp->tcp_ms_we_have_waited = 0;
2404 tcp->tcp_last_recv_time = ddi_get_lbolt();
2405 tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
2406 tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2407
2408 tcp->tcp_maxpsz_multiplier = tcps->tcps_maxpsz_multiplier;
2409
2410 /* NOTE: ISS is now set in tcp_set_destination(). */
2411
2412 /* Reset fusion-related fields */
2413 tcp->tcp_fused = B_FALSE;
2414 tcp->tcp_unfusable = B_FALSE;
2415 tcp->tcp_fused_sigurg = B_FALSE;
2416 tcp->tcp_loopback_peer = NULL;
2417
2418 /* We rebuild the header template on the next connect/conn_request */
2419
2420 connp->conn_mlp_type = mlptSingle;
2421
2422 /*
2423 * Init the window scale to the max so tcp_rwnd_set() won't pare
2424 * down tcp_rwnd. tcp_set_destination() will set the right value later.
2425 */
2426 tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
2427 tcp->tcp_rwnd = connp->conn_rcvbuf;
2428
2429 tcp->tcp_cork = B_FALSE;
2430 /*
2431 * Init the tcp_debug option if it wasn't already set. This value
2432 * determines whether TCP
2433 * calls strlog() to print out debug messages. Doing this
2434 * initialization here means that this value is not inherited thru
2435 * tcp_reinit().
2436 */
2437 if (!connp->conn_debug)
2438 connp->conn_debug = tcps->tcps_dbg;
2439 }
2440
2441 /*
2442 * Update the TCP connection according to change of PMTU.
2443 *
2444 * Path MTU might have changed by either increase or decrease, so need to
2445 * adjust the MSS based on the value of ixa_pmtu. No need to handle tiny
2446 * or negative MSS, since tcp_mss_set() will do it.
2447 */
2448 void
2449 tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only)
2450 {
2451 uint32_t pmtu;
2452 int32_t mss;
2453 conn_t *connp = tcp->tcp_connp;
2454 ip_xmit_attr_t *ixa = connp->conn_ixa;
2455 iaflags_t ixaflags;
2456
2457 if (tcp->tcp_tcps->tcps_ignore_path_mtu)
2458 return;
2459
2460 if (tcp->tcp_state < TCPS_ESTABLISHED)
2461 return;
2462
2463 /*
2464 * Always call ip_get_pmtu() to make sure that IP has updated
2465 * ixa_flags properly.
2466 */
2467 pmtu = ip_get_pmtu(ixa);
2468 ixaflags = ixa->ixa_flags;
2469
2470 /*
2471 * Calculate the MSS by decreasing the PMTU by conn_ht_iphc_len and
2472 * IPsec overhead if applied. Make sure to use the most recent
2473 * IPsec information.
2474 */
2475 mss = pmtu - connp->conn_ht_iphc_len - conn_ipsec_length(connp);
2476
2477 /*
2478 * Nothing to change, so just return.
2479 */
2480 if (mss == tcp->tcp_mss)
2481 return;
2482
2483 /*
2484 * Currently, for ICMP errors, only PMTU decrease is handled.
2485 */
2486 if (mss > tcp->tcp_mss && decrease_only)
2487 return;
2488
2489 DTRACE_PROBE2(tcp_update_pmtu, int32_t, tcp->tcp_mss, uint32_t, mss);
2490
2491 /*
2492 * Update ixa_fragsize and ixa_pmtu.
2493 */
2494 ixa->ixa_fragsize = ixa->ixa_pmtu = pmtu;
2495
2496 /*
2497 * Adjust MSS and all relevant variables.
2498 */
2499 tcp_mss_set(tcp, mss);
2500
2501 /*
2502 * If the PMTU is below the min size maintained by IP, then ip_get_pmtu
2503 * has set IXAF_PMTU_TOO_SMALL and cleared IXAF_PMTU_IPV4_DF. Since TCP
2504 * has a (potentially different) min size we do the same. Make sure to
2505 * clear IXAF_DONTFRAG, which is used by IP to decide whether to
2506 * fragment the packet.
2507 *
2508 * LSO over IPv6 can not be fragmented. So need to disable LSO
2509 * when IPv6 fragmentation is needed.
2510 */
2511 if (mss < tcp->tcp_tcps->tcps_mss_min)
2512 ixaflags |= IXAF_PMTU_TOO_SMALL;
2513
2514 if (ixaflags & IXAF_PMTU_TOO_SMALL)
2515 ixaflags &= ~(IXAF_DONTFRAG | IXAF_PMTU_IPV4_DF);
2516
2517 if ((connp->conn_ipversion == IPV4_VERSION) &&
2518 !(ixaflags & IXAF_PMTU_IPV4_DF)) {
2519 tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
2520 }
2521 ixa->ixa_flags = ixaflags;
2522 }
2523
2524 int
2525 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
2526 {
2527 conn_t *connp = tcp->tcp_connp;
2528 queue_t *q = connp->conn_rq;
2529 int32_t mss = tcp->tcp_mss;
2530 int maxpsz;
2531
2532 if (TCP_IS_DETACHED(tcp))
2533 return (mss);
2534 if (tcp->tcp_fused) {
2535 maxpsz = tcp_fuse_maxpsz(tcp);
2536 mss = INFPSZ;
2537 } else if (tcp->tcp_maxpsz_multiplier == 0) {
2538 /*
2539 * Set the sd_qn_maxpsz according to the socket send buffer
2540 * size, and sd_maxblk to INFPSZ (-1). This will essentially
2541 * instruct the stream head to copyin user data into contiguous
2542 * kernel-allocated buffers without breaking it up into smaller
2543 * chunks. We round up the buffer size to the nearest SMSS.
2544 */
2545 maxpsz = MSS_ROUNDUP(connp->conn_sndbuf, mss);
2546 mss = INFPSZ;
2547 } else {
2548 /*
2549 * Set sd_qn_maxpsz to approx half the (receivers) buffer
2550 * (and a multiple of the mss). This instructs the stream
2551 * head to break down larger than SMSS writes into SMSS-
2552 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
2553 */
2554 maxpsz = tcp->tcp_maxpsz_multiplier * mss;
2555 if (maxpsz > connp->conn_sndbuf / 2) {
2556 maxpsz = connp->conn_sndbuf / 2;
2557 /* Round up to nearest mss */
2558 maxpsz = MSS_ROUNDUP(maxpsz, mss);
2559 }
2560 }
2561
2562 (void) proto_set_maxpsz(q, connp, maxpsz);
2563 if (!(IPCL_IS_NONSTR(connp)))
2564 connp->conn_wq->q_maxpsz = maxpsz;
2565 if (set_maxblk)
2566 (void) proto_set_tx_maxblk(q, connp, mss);
2567 return (mss);
2568 }
2569
2570 /* For /dev/tcp aka AF_INET open */
2571 static int
2572 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
2573 {
2574 return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
2575 }
2576
2577 /* For /dev/tcp6 aka AF_INET6 open */
2578 static int
2579 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
2580 {
2581 return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
2582 }
2583
2584 conn_t *
2585 tcp_create_common(cred_t *credp, boolean_t isv6, boolean_t issocket,
2586 int *errorp)
2587 {
2588 tcp_t *tcp = NULL;
2589 conn_t *connp;
2590 zoneid_t zoneid;
2591 tcp_stack_t *tcps;
2592 squeue_t *sqp;
2593
2594 ASSERT(errorp != NULL);
2595 /*
2596 * Find the proper zoneid and netstack.
2597 */
2598 /*
2599 * Special case for install: miniroot needs to be able to
2600 * access files via NFS as though it were always in the
2601 * global zone.
2602 */
2603 if (credp == kcred && nfs_global_client_only != 0) {
2604 zoneid = GLOBAL_ZONEID;
2605 tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
2606 netstack_tcp;
2607 ASSERT(tcps != NULL);
2608 } else {
2609 netstack_t *ns;
2610 int err;
2611
2612 if ((err = secpolicy_basic_net_access(credp)) != 0) {
2613 *errorp = err;
2614 return (NULL);
2615 }
2616
2617 ns = netstack_find_by_cred(credp);
2618 ASSERT(ns != NULL);
2619 tcps = ns->netstack_tcp;
2620 ASSERT(tcps != NULL);
2621
2622 /*
2623 * For exclusive stacks we set the zoneid to zero
2624 * to make TCP operate as if in the global zone.
2625 */
2626 if (tcps->tcps_netstack->netstack_stackid !=
2627 GLOBAL_NETSTACKID)
2628 zoneid = GLOBAL_ZONEID;
2629 else
2630 zoneid = crgetzoneid(credp);
2631 }
2632
2633 sqp = IP_SQUEUE_GET((uint_t)gethrtime());
2634 connp = (conn_t *)tcp_get_conn(sqp, tcps);
2635 /*
2636 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
2637 * so we drop it by one.
2638 */
2639 netstack_rele(tcps->tcps_netstack);
2640 if (connp == NULL) {
2641 *errorp = ENOSR;
2642 return (NULL);
2643 }
2644 ASSERT(connp->conn_ixa->ixa_protocol == connp->conn_proto);
2645
2646 connp->conn_sqp = sqp;
2647 connp->conn_initial_sqp = connp->conn_sqp;
2648 connp->conn_ixa->ixa_sqp = connp->conn_sqp;
2649 tcp = connp->conn_tcp;
2650
2651 /*
2652 * Besides asking IP to set the checksum for us, have conn_ip_output
2653 * to do the following checks when necessary:
2654 *
2655 * IXAF_VERIFY_SOURCE: drop packets when our outer source goes invalid
2656 * IXAF_VERIFY_PMTU: verify PMTU changes
2657 * IXAF_VERIFY_LSO: verify LSO capability changes
2658 */
2659 connp->conn_ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
2660 IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO;
2661
2662 if (!tcps->tcps_dev_flow_ctl)
2663 connp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
2664
2665 if (isv6) {
2666 connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
2667 connp->conn_ipversion = IPV6_VERSION;
2668 connp->conn_family = AF_INET6;
2669 tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
2670 connp->conn_default_ttl = tcps->tcps_ipv6_hoplimit;
2671 } else {
2672 connp->conn_ipversion = IPV4_VERSION;
2673 connp->conn_family = AF_INET;
2674 tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
2675 connp->conn_default_ttl = tcps->tcps_ipv4_ttl;
2676 }
2677 connp->conn_xmit_ipp.ipp_unicast_hops = connp->conn_default_ttl;
2678
2679 crhold(credp);
2680 connp->conn_cred = credp;
2681 connp->conn_cpid = curproc->p_pid;
2682 connp->conn_open_time = ddi_get_lbolt64();
2683
2684 /* Cache things in the ixa without any refhold */
2685 ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
2686 connp->conn_ixa->ixa_cred = credp;
2687 connp->conn_ixa->ixa_cpid = connp->conn_cpid;
2688
2689 connp->conn_zoneid = zoneid;
2690 /* conn_allzones can not be set this early, hence no IPCL_ZONEID */
2691 connp->conn_ixa->ixa_zoneid = zoneid;
2692 connp->conn_mlp_type = mlptSingle;
2693 ASSERT(connp->conn_netstack == tcps->tcps_netstack);
2694 ASSERT(tcp->tcp_tcps == tcps);
2695
2696 /*
2697 * If the caller has the process-wide flag set, then default to MAC
2698 * exempt mode. This allows read-down to unlabeled hosts.
2699 */
2700 if (getpflags(NET_MAC_AWARE, credp) != 0)
2701 connp->conn_mac_mode = CONN_MAC_AWARE;
2702
2703 connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
2704
2705 if (issocket) {
2706 tcp->tcp_issocket = 1;
2707 }
2708
2709 connp->conn_rcvbuf = tcps->tcps_recv_hiwat;
2710 connp->conn_sndbuf = tcps->tcps_xmit_hiwat;
2711 if (tcps->tcps_snd_lowat_fraction != 0) {
2712 connp->conn_sndlowat = connp->conn_sndbuf /
2713 tcps->tcps_snd_lowat_fraction;
2714 } else {
2715 connp->conn_sndlowat = tcps->tcps_xmit_lowat;
2716 }
2717 connp->conn_so_type = SOCK_STREAM;
2718 connp->conn_wroff = connp->conn_ht_iphc_allocated +
2719 tcps->tcps_wroff_xtra;
2720
2721 SOCK_CONNID_INIT(tcp->tcp_connid);
2722 /* DTrace ignores this - it isn't a tcp:::state-change */
2723 tcp->tcp_state = TCPS_IDLE;
2724 tcp_init_values(tcp, NULL);
2725 return (connp);
2726 }
2727
2728 static int
2729 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
2730 boolean_t isv6)
2731 {
2732 tcp_t *tcp = NULL;
2733 conn_t *connp = NULL;
2734 int err;
2735 vmem_t *minor_arena = NULL;
2736 dev_t conn_dev;
2737 boolean_t issocket;
2738
2739 if (q->q_ptr != NULL)
2740 return (0);
2741
2742 if (sflag == MODOPEN)
2743 return (EINVAL);
2744
2745 if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
2746 ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
2747 minor_arena = ip_minor_arena_la;
2748 } else {
2749 /*
2750 * Either minor numbers in the large arena were exhausted
2751 * or a non socket application is doing the open.
2752 * Try to allocate from the small arena.
2753 */
2754 if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
2755 return (EBUSY);
2756 }
2757 minor_arena = ip_minor_arena_sa;
2758 }
2759
2760 ASSERT(minor_arena != NULL);
2761
2762 *devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
2763
2764 if (flag & SO_FALLBACK) {
2765 /*
2766 * Non streams socket needs a stream to fallback to
2767 */
2768 RD(q)->q_ptr = (void *)conn_dev;
2769 WR(q)->q_qinfo = &tcp_fallback_sock_winit;
2770 WR(q)->q_ptr = (void *)minor_arena;
2771 qprocson(q);
2772 return (0);
2773 } else if (flag & SO_ACCEPTOR) {
2774 q->q_qinfo = &tcp_acceptor_rinit;
2775 /*
2776 * the conn_dev and minor_arena will be subsequently used by
2777 * tcp_tli_accept() and tcp_tpi_close_accept() to figure out
2778 * the minor device number for this connection from the q_ptr.
2779 */
2780 RD(q)->q_ptr = (void *)conn_dev;
2781 WR(q)->q_qinfo = &tcp_acceptor_winit;
2782 WR(q)->q_ptr = (void *)minor_arena;
2783 qprocson(q);
2784 return (0);
2785 }
2786
2787 issocket = flag & SO_SOCKSTR;
2788 connp = tcp_create_common(credp, isv6, issocket, &err);
2789
2790 if (connp == NULL) {
2791 inet_minor_free(minor_arena, conn_dev);
2792 q->q_ptr = WR(q)->q_ptr = NULL;
2793 return (err);
2794 }
2795
2796 connp->conn_rq = q;
2797 connp->conn_wq = WR(q);
2798 q->q_ptr = WR(q)->q_ptr = connp;
2799
2800 connp->conn_dev = conn_dev;
2801 connp->conn_minor_arena = minor_arena;
2802
2803 ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
2804 ASSERT(WR(q)->q_qinfo == &tcp_winit);
2805
2806 tcp = connp->conn_tcp;
2807
2808 if (issocket) {
2809 WR(q)->q_qinfo = &tcp_sock_winit;
2810 } else {
2811 #ifdef _ILP32
2812 tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
2813 #else
2814 tcp->tcp_acceptor_id = conn_dev;
2815 #endif /* _ILP32 */
2816 tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
2817 }
2818
2819 /*
2820 * Put the ref for TCP. Ref for IP was already put
2821 * by ipcl_conn_create. Also Make the conn_t globally
2822 * visible to walkers
2823 */
2824 mutex_enter(&connp->conn_lock);
2825 CONN_INC_REF_LOCKED(connp);
2826 ASSERT(connp->conn_ref == 2);
2827 connp->conn_state_flags &= ~CONN_INCIPIENT;
2828 mutex_exit(&connp->conn_lock);
2829
2830 qprocson(q);
2831 return (0);
2832 }
2833
2834 /*
2835 * Build/update the tcp header template (in conn_ht_iphc) based on
2836 * conn_xmit_ipp. The headers include ip6_t, any extension
2837 * headers, and the maximum size tcp header (to avoid reallocation
2838 * on the fly for additional tcp options).
2839 *
2840 * Assumes the caller has already set conn_{faddr,laddr,fport,lport,flowinfo}.
2841 * Returns failure if can't allocate memory.
2842 */
2843 int
2844 tcp_build_hdrs(tcp_t *tcp)
2845 {
2846 tcp_stack_t *tcps = tcp->tcp_tcps;
2847 conn_t *connp = tcp->tcp_connp;
2848 char buf[TCP_MAX_HDR_LENGTH];
2849 uint_t buflen;
2850 uint_t ulplen = TCP_MIN_HEADER_LENGTH;
2851 uint_t extralen = TCP_MAX_TCP_OPTIONS_LENGTH;
2852 tcpha_t *tcpha;
2853 uint32_t cksum;
2854 int error;
2855
2856 /*
2857 * We might be called after the connection is set up, and we might
2858 * have TS options already in the TCP header. Thus we save any
2859 * existing tcp header.
2860 */
2861 buflen = connp->conn_ht_ulp_len;
2862 if (buflen != 0) {
2863 bcopy(connp->conn_ht_ulp, buf, buflen);
2864 extralen -= buflen - ulplen;
2865 ulplen = buflen;
2866 }
2867
2868 /* Grab lock to satisfy ASSERT; TCP is serialized using squeue */
2869 mutex_enter(&connp->conn_lock);
2870 error = conn_build_hdr_template(connp, ulplen, extralen,
2871 &connp->conn_laddr_v6, &connp->conn_faddr_v6, connp->conn_flowinfo);
2872 mutex_exit(&connp->conn_lock);
2873 if (error != 0)
2874 return (error);
2875
2876 /*
2877 * Any routing header/option has been massaged. The checksum difference
2878 * is stored in conn_sum for later use.
2879 */
2880 tcpha = (tcpha_t *)connp->conn_ht_ulp;
2881 tcp->tcp_tcpha = tcpha;
2882
2883 /* restore any old tcp header */
2884 if (buflen != 0) {
2885 bcopy(buf, connp->conn_ht_ulp, buflen);
2886 } else {
2887 tcpha->tha_sum = 0;
2888 tcpha->tha_urp = 0;
2889 tcpha->tha_ack = 0;
2890 tcpha->tha_offset_and_reserved = (5 << 4);
2891 tcpha->tha_lport = connp->conn_lport;
2892 tcpha->tha_fport = connp->conn_fport;
2893 }
2894
2895 /*
2896 * IP wants our header length in the checksum field to
2897 * allow it to perform a single pseudo-header+checksum
2898 * calculation on behalf of TCP.
2899 * Include the adjustment for a source route once IP_OPTIONS is set.
2900 */
2901 cksum = sizeof (tcpha_t) + connp->conn_sum;
2902 cksum = (cksum >> 16) + (cksum & 0xFFFF);
2903 ASSERT(cksum < 0x10000);
2904 tcpha->tha_sum = htons(cksum);
2905
2906 if (connp->conn_ipversion == IPV4_VERSION)
2907 tcp->tcp_ipha = (ipha_t *)connp->conn_ht_iphc;
2908 else
2909 tcp->tcp_ip6h = (ip6_t *)connp->conn_ht_iphc;
2910
2911 if (connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra >
2912 connp->conn_wroff) {
2913 connp->conn_wroff = connp->conn_ht_iphc_allocated +
2914 tcps->tcps_wroff_xtra;
2915 (void) proto_set_tx_wroff(connp->conn_rq, connp,
2916 connp->conn_wroff);
2917 }
2918 return (0);
2919 }
2920
2921 /*
2922 * tcp_rwnd_set() is called to adjust the receive window to a desired value.
2923 * We do not allow the receive window to shrink. After setting rwnd,
2924 * set the flow control hiwat of the stream.
2925 *
2926 * This function is called in 2 cases:
2927 *
2928 * 1) Before data transfer begins, in tcp_input_listener() for accepting a
2929 * connection (passive open) and in tcp_input_data() for active connect.
2930 * This is called after tcp_mss_set() when the desired MSS value is known.
2931 * This makes sure that our window size is a mutiple of the other side's
2932 * MSS.
2933 * 2) Handling SO_RCVBUF option.
2934 *
2935 * It is ASSUMED that the requested size is a multiple of the current MSS.
2936 *
2937 * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
2938 * user requests so.
2939 */
2940 int
2941 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
2942 {
2943 uint32_t mss = tcp->tcp_mss;
2944 uint32_t old_max_rwnd;
2945 uint32_t max_transmittable_rwnd;
2946 boolean_t tcp_detached = TCP_IS_DETACHED(tcp);
2947 tcp_stack_t *tcps = tcp->tcp_tcps;
2948 conn_t *connp = tcp->tcp_connp;
2949
2950 /*
2951 * Insist on a receive window that is at least
2952 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
2953 * funny TCP interactions of Nagle algorithm, SWS avoidance
2954 * and delayed acknowledgement.
2955 */
2956 rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
2957
2958 if (tcp->tcp_fused) {
2959 size_t sth_hiwat;
2960 tcp_t *peer_tcp = tcp->tcp_loopback_peer;
2961
2962 ASSERT(peer_tcp != NULL);
2963 sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
2964 if (!tcp_detached) {
2965 (void) proto_set_rx_hiwat(connp->conn_rq, connp,
2966 sth_hiwat);
2967 tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
2968 }
2969
2970 /* Caller could have changed tcp_rwnd; update tha_win */
2971 if (tcp->tcp_tcpha != NULL) {
2972 tcp->tcp_tcpha->tha_win =
2973 htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
2974 }
2975 if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
2976 tcp->tcp_cwnd_max = rwnd;
2977
2978 /*
2979 * In the fusion case, the maxpsz stream head value of
2980 * our peer is set according to its send buffer size
2981 * and our receive buffer size; since the latter may
2982 * have changed we need to update the peer's maxpsz.
2983 */
2984 (void) tcp_maxpsz_set(peer_tcp, B_TRUE);
2985 return (sth_hiwat);
2986 }
2987
2988 if (tcp_detached)
2989 old_max_rwnd = tcp->tcp_rwnd;
2990 else
2991 old_max_rwnd = connp->conn_rcvbuf;
2992
2993
2994 /*
2995 * If window size info has already been exchanged, TCP should not
2996 * shrink the window. Shrinking window is doable if done carefully.
2997 * We may add that support later. But so far there is not a real
2998 * need to do that.
2999 */
3000 if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
3001 /* MSS may have changed, do a round up again. */
3002 rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
3003 }
3004
3005 /*
3006 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
3007 * can be applied even before the window scale option is decided.
3008 */
3009 max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
3010 if (rwnd > max_transmittable_rwnd) {
3011 rwnd = max_transmittable_rwnd -
3012 (max_transmittable_rwnd % mss);
3013 if (rwnd < mss)
3014 rwnd = max_transmittable_rwnd;
3015 /*
3016 * If we're over the limit we may have to back down tcp_rwnd.
3017 * The increment below won't work for us. So we set all three
3018 * here and the increment below will have no effect.
3019 */
3020 tcp->tcp_rwnd = old_max_rwnd = rwnd;
3021 }
3022 if (tcp->tcp_localnet) {
3023 tcp->tcp_rack_abs_max =
3024 MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
3025 } else {
3026 /*
3027 * For a remote host on a different subnet (through a router),
3028 * we ack every other packet to be conforming to RFC1122.
3029 * tcp_deferred_acks_max is default to 2.
3030 */
3031 tcp->tcp_rack_abs_max =
3032 MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
3033 }
3034 if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
3035 tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
3036 else
3037 tcp->tcp_rack_cur_max = 0;
3038 /*
3039 * Increment the current rwnd by the amount the maximum grew (we
3040 * can not overwrite it since we might be in the middle of a
3041 * connection.)
3042 */
3043 tcp->tcp_rwnd += rwnd - old_max_rwnd;
3044 connp->conn_rcvbuf = rwnd;
3045
3046 /* Are we already connected? */
3047 if (tcp->tcp_tcpha != NULL) {
3048 tcp->tcp_tcpha->tha_win =
3049 htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
3050 }
3051
3052 if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
3053 tcp->tcp_cwnd_max = rwnd;
3054
3055 if (tcp_detached)
3056 return (rwnd);
3057
3058 tcp_set_recv_threshold(tcp, rwnd >> 3);
3059
3060 (void) proto_set_rx_hiwat(connp->conn_rq, connp, rwnd);
3061 return (rwnd);
3062 }
3063
3064 int
3065 tcp_do_unbind(conn_t *connp)
3066 {
3067 tcp_t *tcp = connp->conn_tcp;
3068 int32_t oldstate;
3069
3070 switch (tcp->tcp_state) {
3071 case TCPS_BOUND:
3072 case TCPS_LISTEN:
3073 break;
3074 default:
3075 return (-TOUTSTATE);
3076 }
3077
3078 /*
3079 * Need to clean up all the eagers since after the unbind, segments
3080 * will no longer be delivered to this listener stream.
3081 */
3082 mutex_enter(&tcp->tcp_eager_lock);
3083 if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3084 tcp_eager_cleanup(tcp, 0);
3085 }
3086 mutex_exit(&tcp->tcp_eager_lock);
3087
3088 /* Clean up the listener connection counter if necessary. */
3089 if (tcp->tcp_listen_cnt != NULL)
3090 TCP_DECR_LISTEN_CNT(tcp);
3091 connp->conn_laddr_v6 = ipv6_all_zeros;
3092 connp->conn_saddr_v6 = ipv6_all_zeros;
3093 tcp_bind_hash_remove(tcp);
3094 oldstate = tcp->tcp_state;
3095 tcp->tcp_state = TCPS_IDLE;
3096 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
3097 connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
3098 int32_t, oldstate);
3099
3100 ip_unbind(connp);
3101 bzero(&connp->conn_ports, sizeof (connp->conn_ports));
3102
3103 return (0);
3104 }
3105
3106 /*
3107 * Collect protocol properties to send to the upper handle.
3108 */
3109 void
3110 tcp_get_proto_props(tcp_t *tcp, struct sock_proto_props *sopp)
3111 {
3112 conn_t *connp = tcp->tcp_connp;
3113
3114 sopp->sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
3115 sopp->sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
3116
3117 sopp->sopp_rxhiwat = tcp->tcp_fused ?
3118 tcp_fuse_set_rcv_hiwat(tcp, connp->conn_rcvbuf) :
3119 connp->conn_rcvbuf;
3120 /*
3121 * Determine what write offset value to use depending on SACK and
3122 * whether the endpoint is fused or not.
3123 */
3124 if (tcp->tcp_fused) {
3125 ASSERT(tcp->tcp_loopback);
3126 ASSERT(tcp->tcp_loopback_peer != NULL);
3127 /*
3128 * For fused tcp loopback, set the stream head's write
3129 * offset value to zero since we won't be needing any room
3130 * for TCP/IP headers. This would also improve performance
3131 * since it would reduce the amount of work done by kmem.
3132 * Non-fused tcp loopback case is handled separately below.
3133 */
3134 sopp->sopp_wroff = 0;
3135 /*
3136 * Update the peer's transmit parameters according to
3137 * our recently calculated high water mark value.
3138 */
3139 (void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
3140 } else if (tcp->tcp_snd_sack_ok) {
3141 sopp->sopp_wroff = connp->conn_ht_iphc_allocated +
3142 (tcp->tcp_loopback ? 0 : tcp->tcp_tcps->tcps_wroff_xtra);
3143 } else {
3144 sopp->sopp_wroff = connp->conn_ht_iphc_len +
3145 (tcp->tcp_loopback ? 0 : tcp->tcp_tcps->tcps_wroff_xtra);
3146 }
3147
3148 if (tcp->tcp_loopback) {
3149 sopp->sopp_flags |= SOCKOPT_LOOPBACK;
3150 sopp->sopp_loopback = B_TRUE;
3151 }
3152 }
3153
3154 /*
3155 * Check the usability of ZEROCOPY. It's instead checking the flag set by IP.
3156 */
3157 boolean_t
3158 tcp_zcopy_check(tcp_t *tcp)
3159 {
3160 conn_t *connp = tcp->tcp_connp;
3161 ip_xmit_attr_t *ixa = connp->conn_ixa;
3162 boolean_t zc_enabled = B_FALSE;
3163 tcp_stack_t *tcps = tcp->tcp_tcps;
3164
3165 if (do_tcpzcopy == 2)
3166 zc_enabled = B_TRUE;
3167 else if ((do_tcpzcopy == 1) && (ixa->ixa_flags & IXAF_ZCOPY_CAPAB))
3168 zc_enabled = B_TRUE;
3169
3170 tcp->tcp_snd_zcopy_on = zc_enabled;
3171 if (!TCP_IS_DETACHED(tcp)) {
3172 if (zc_enabled) {
3173 ixa->ixa_flags |= IXAF_VERIFY_ZCOPY;
3174 (void) proto_set_tx_copyopt(connp->conn_rq, connp,
3175 ZCVMSAFE);
3176 TCP_STAT(tcps, tcp_zcopy_on);
3177 } else {
3178 ixa->ixa_flags &= ~IXAF_VERIFY_ZCOPY;
3179 (void) proto_set_tx_copyopt(connp->conn_rq, connp,
3180 ZCVMUNSAFE);
3181 TCP_STAT(tcps, tcp_zcopy_off);
3182 }
3183 }
3184 return (zc_enabled);
3185 }
3186
3187 /*
3188 * Backoff from a zero-copy message by copying data to a new allocated
3189 * message and freeing the original desballoca'ed segmapped message.
3190 *
3191 * This function is called by following two callers:
3192 * 1. tcp_timer: fix_xmitlist is set to B_TRUE, because it's safe to free
3193 * the origial desballoca'ed message and notify sockfs. This is in re-
3194 * transmit state.
3195 * 2. tcp_output: fix_xmitlist is set to B_FALSE. Flag STRUIO_ZCNOTIFY need
3196 * to be copied to new message.
3197 */
3198 mblk_t *
3199 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, boolean_t fix_xmitlist)
3200 {
3201 mblk_t *nbp;
3202 mblk_t *head = NULL;
3203 mblk_t *tail = NULL;
3204 tcp_stack_t *tcps = tcp->tcp_tcps;
3205
3206 ASSERT(bp != NULL);
3207 while (bp != NULL) {
3208 if (IS_VMLOANED_MBLK(bp)) {
3209 TCP_STAT(tcps, tcp_zcopy_backoff);
3210 if ((nbp = copyb(bp)) == NULL) {
3211 tcp->tcp_xmit_zc_clean = B_FALSE;
3212 if (tail != NULL)
3213 tail->b_cont = bp;
3214 return ((head == NULL) ? bp : head);
3215 }
3216
3217 if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
3218 if (fix_xmitlist)
3219 tcp_zcopy_notify(tcp);
3220 else
3221 nbp->b_datap->db_struioflag |=
3222 STRUIO_ZCNOTIFY;
3223 }
3224 nbp->b_cont = bp->b_cont;
3225
3226 /*
3227 * Copy saved information and adjust tcp_xmit_tail
3228 * if needed.
3229 */
3230 if (fix_xmitlist) {
3231 nbp->b_prev = bp->b_prev;
3232 nbp->b_next = bp->b_next;
3233
3234 if (tcp->tcp_xmit_tail == bp)
3235 tcp->tcp_xmit_tail = nbp;
3236 }
3237
3238 /* Free the original message. */
3239 bp->b_prev = NULL;
3240 bp->b_next = NULL;
3241 freeb(bp);
3242
3243 bp = nbp;
3244 }
3245
3246 if (head == NULL) {
3247 head = bp;
3248 }
3249 if (tail == NULL) {
3250 tail = bp;
3251 } else {
3252 tail->b_cont = bp;
3253 tail = bp;
3254 }
3255
3256 /* Move forward. */
3257 bp = bp->b_cont;
3258 }
3259
3260 if (fix_xmitlist) {
3261 tcp->tcp_xmit_last = tail;
3262 tcp->tcp_xmit_zc_clean = B_TRUE;
3263 }
3264
3265 return (head);
3266 }
3267
3268 void
3269 tcp_zcopy_notify(tcp_t *tcp)
3270 {
3271 struct stdata *stp;
3272 conn_t *connp;
3273
3274 if (tcp->tcp_detached)
3275 return;
3276 connp = tcp->tcp_connp;
3277 if (IPCL_IS_NONSTR(connp)) {
3278 (*connp->conn_upcalls->su_zcopy_notify)
3279 (connp->conn_upper_handle);
3280 return;
3281 }
3282 stp = STREAM(connp->conn_rq);
3283 mutex_enter(&stp->sd_lock);
3284 stp->sd_flag |= STZCNOTIFY;
3285 cv_broadcast(&stp->sd_zcopy_wait);
3286 mutex_exit(&stp->sd_lock);
3287 }
3288
3289 /*
3290 * Update the TCP connection according to change of LSO capability.
3291 */
3292 static void
3293 tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa)
3294 {
3295 /*
3296 * We check against IPv4 header length to preserve the old behavior
3297 * of only enabling LSO when there are no IP options.
3298 * But this restriction might not be necessary at all. Before removing
3299 * it, need to verify how LSO is handled for source routing case, with
3300 * which IP does software checksum.
3301 *
3302 * For IPv6, whenever any extension header is needed, LSO is supressed.
3303 */
3304 if (ixa->ixa_ip_hdr_length != ((ixa->ixa_flags & IXAF_IS_IPV4) ?
3305 IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN))
3306 return;
3307
3308 /*
3309 * Either the LSO capability newly became usable, or it has changed.
3310 */
3311 if (ixa->ixa_flags & IXAF_LSO_CAPAB) {
3312 ill_lso_capab_t *lsoc = &ixa->ixa_lso_capab;
3313
3314 ASSERT(lsoc->ill_lso_max > 0);
3315 tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH, lsoc->ill_lso_max);
3316
3317 DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
3318 boolean_t, B_TRUE, uint32_t, tcp->tcp_lso_max);
3319
3320 /*
3321 * If LSO to be enabled, notify the STREAM header with larger
3322 * data block.
3323 */
3324 if (!tcp->tcp_lso)
3325 tcp->tcp_maxpsz_multiplier = 0;
3326
3327 tcp->tcp_lso = B_TRUE;
3328 TCP_STAT(tcp->tcp_tcps, tcp_lso_enabled);
3329 } else { /* LSO capability is not usable any more. */
3330 DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
3331 boolean_t, B_FALSE, uint32_t, tcp->tcp_lso_max);
3332
3333 /*
3334 * If LSO to be disabled, notify the STREAM header with smaller
3335 * data block. And need to restore fragsize to PMTU.
3336 */
3337 if (tcp->tcp_lso) {
3338 tcp->tcp_maxpsz_multiplier =
3339 tcp->tcp_tcps->tcps_maxpsz_multiplier;
3340 ixa->ixa_fragsize = ixa->ixa_pmtu;
3341 tcp->tcp_lso = B_FALSE;
3342 TCP_STAT(tcp->tcp_tcps, tcp_lso_disabled);
3343 }
3344 }
3345
3346 (void) tcp_maxpsz_set(tcp, B_TRUE);
3347 }
3348
3349 /*
3350 * Update the TCP connection according to change of ZEROCOPY capability.
3351 */
3352 static void
3353 tcp_update_zcopy(tcp_t *tcp)
3354 {
3355 conn_t *connp = tcp->tcp_connp;
3356 tcp_stack_t *tcps = tcp->tcp_tcps;
3357
3358 if (tcp->tcp_snd_zcopy_on) {
3359 tcp->tcp_snd_zcopy_on = B_FALSE;
3360 if (!TCP_IS_DETACHED(tcp)) {
3361 (void) proto_set_tx_copyopt(connp->conn_rq, connp,
3362 ZCVMUNSAFE);
3363 TCP_STAT(tcps, tcp_zcopy_off);
3364 }
3365 } else {
3366 tcp->tcp_snd_zcopy_on = B_TRUE;
3367 if (!TCP_IS_DETACHED(tcp)) {
3368 (void) proto_set_tx_copyopt(connp->conn_rq, connp,
3369 ZCVMSAFE);
3370 TCP_STAT(tcps, tcp_zcopy_on);
3371 }
3372 }
3373 }
3374
3375 /*
3376 * Notify function registered with ip_xmit_attr_t. It's called in the squeue
3377 * so it's safe to update the TCP connection.
3378 */
3379 /* ARGSUSED1 */
3380 static void
3381 tcp_notify(void *arg, ip_xmit_attr_t *ixa, ixa_notify_type_t ntype,
3382 ixa_notify_arg_t narg)
3383 {
3384 tcp_t *tcp = (tcp_t *)arg;
3385 conn_t *connp = tcp->tcp_connp;
3386
3387 switch (ntype) {
3388 case IXAN_LSO:
3389 tcp_update_lso(tcp, connp->conn_ixa);
3390 break;
3391 case IXAN_PMTU:
3392 tcp_update_pmtu(tcp, B_FALSE);
3393 break;
3394 case IXAN_ZCOPY:
3395 tcp_update_zcopy(tcp);
3396 break;
3397 default:
3398 break;
3399 }
3400 }
3401
3402 /*
3403 * The TCP write service routine should never be called...
3404 */
3405 /* ARGSUSED */
3406 static int
3407 tcp_wsrv(queue_t *q)
3408 {
3409 tcp_stack_t *tcps = Q_TO_TCP(q)->tcp_tcps;
3410
3411 TCP_STAT(tcps, tcp_wsrv_called);
3412 return (0);
3413 }
3414
3415 /*
3416 * Hash list lookup routine for tcp_t structures.
3417 * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
3418 */
3419 tcp_t *
3420 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
3421 {
3422 tf_t *tf;
3423 tcp_t *tcp;
3424
3425 tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
3426 mutex_enter(&tf->tf_lock);
3427 for (tcp = tf->tf_tcp; tcp != NULL;
3428 tcp = tcp->tcp_acceptor_hash) {
3429 if (tcp->tcp_acceptor_id == id) {
3430 CONN_INC_REF(tcp->tcp_connp);
3431 mutex_exit(&tf->tf_lock);
3432 return (tcp);
3433 }
3434 }
3435 mutex_exit(&tf->tf_lock);
3436 return (NULL);
3437 }
3438
3439 /*
3440 * Hash list insertion routine for tcp_t structures.
3441 */
3442 void
3443 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
3444 {
3445 tf_t *tf;
3446 tcp_t **tcpp;
3447 tcp_t *tcpnext;
3448 tcp_stack_t *tcps = tcp->tcp_tcps;
3449
3450 tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
3451
3452 if (tcp->tcp_ptpahn != NULL)
3453 tcp_acceptor_hash_remove(tcp);
3454 tcpp = &tf->tf_tcp;
3455 mutex_enter(&tf->tf_lock);
3456 tcpnext = tcpp[0];
3457 if (tcpnext)
3458 tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
3459 tcp->tcp_acceptor_hash = tcpnext;
3460 tcp->tcp_ptpahn = tcpp;
3461 tcpp[0] = tcp;
3462 tcp->tcp_acceptor_lockp = &tf->tf_lock; /* For tcp_*_hash_remove */
3463 mutex_exit(&tf->tf_lock);
3464 }
3465
3466 /*
3467 * Hash list removal routine for tcp_t structures.
3468 */
3469 void
3470 tcp_acceptor_hash_remove(tcp_t *tcp)
3471 {
3472 tcp_t *tcpnext;
3473 kmutex_t *lockp;
3474
3475 /*
3476 * Extract the lock pointer in case there are concurrent
3477 * hash_remove's for this instance.
3478 */
3479 lockp = tcp->tcp_acceptor_lockp;
3480
3481 if (tcp->tcp_ptpahn == NULL)
3482 return;
3483
3484 ASSERT(lockp != NULL);
3485 mutex_enter(lockp);
3486 if (tcp->tcp_ptpahn) {
3487 tcpnext = tcp->tcp_acceptor_hash;
3488 if (tcpnext) {
3489 tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
3490 tcp->tcp_acceptor_hash = NULL;
3491 }
3492 *tcp->tcp_ptpahn = tcpnext;
3493 tcp->tcp_ptpahn = NULL;
3494 }
3495 mutex_exit(lockp);
3496 tcp->tcp_acceptor_lockp = NULL;
3497 }
3498
3499 /*
3500 * Type three generator adapted from the random() function in 4.4 BSD:
3501 */
3502
3503 /*
3504 * Copyright (c) 1983, 1993
3505 * The Regents of the University of California. All rights reserved.
3506 *
3507 * Redistribution and use in source and binary forms, with or without
3508 * modification, are permitted provided that the following conditions
3509 * are met:
3510 * 1. Redistributions of source code must retain the above copyright
3511 * notice, this list of conditions and the following disclaimer.
3512 * 2. Redistributions in binary form must reproduce the above copyright
3513 * notice, this list of conditions and the following disclaimer in the
3514 * documentation and/or other materials provided with the distribution.
3515 * 3. All advertising materials mentioning features or use of this software
3516 * must display the following acknowledgement:
3517 * This product includes software developed by the University of
3518 * California, Berkeley and its contributors.
3519 * 4. Neither the name of the University nor the names of its contributors
3520 * may be used to endorse or promote products derived from this software
3521 * without specific prior written permission.
3522 *
3523 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3524 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3525 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3526 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3527 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3528 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3529 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3530 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3531 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3532 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3533 * SUCH DAMAGE.
3534 */
3535
3536 /* Type 3 -- x**31 + x**3 + 1 */
3537 #define DEG_3 31
3538 #define SEP_3 3
3539
3540
3541 /* Protected by tcp_random_lock */
3542 static int tcp_randtbl[DEG_3 + 1];
3543
3544 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
3545 static int *tcp_random_rptr = &tcp_randtbl[1];
3546
3547 static int *tcp_random_state = &tcp_randtbl[1];
3548 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
3549
3550 kmutex_t tcp_random_lock;
3551
3552 void
3553 tcp_random_init(void)
3554 {
3555 int i;
3556 hrtime_t hrt;
3557 time_t wallclock;
3558 uint64_t result;
3559
3560 /*
3561 * Use high-res timer and current time for seed. Gethrtime() returns
3562 * a longlong, which may contain resolution down to nanoseconds.
3563 * The current time will either be a 32-bit or a 64-bit quantity.
3564 * XOR the two together in a 64-bit result variable.
3565 * Convert the result to a 32-bit value by multiplying the high-order
3566 * 32-bits by the low-order 32-bits.
3567 */
3568
3569 hrt = gethrtime();
3570 (void) drv_getparm(TIME, &wallclock);
3571 result = (uint64_t)wallclock ^ (uint64_t)hrt;
3572 mutex_enter(&tcp_random_lock);
3573 tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
3574 (result & 0xffffffff);
3575
3576 for (i = 1; i < DEG_3; i++)
3577 tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
3578 + 12345;
3579 tcp_random_fptr = &tcp_random_state[SEP_3];
3580 tcp_random_rptr = &tcp_random_state[0];
3581 mutex_exit(&tcp_random_lock);
3582 for (i = 0; i < 10 * DEG_3; i++)
3583 (void) tcp_random();
3584 }
3585
3586 /*
3587 * tcp_random: Return a random number in the range [1 - (128K + 1)].
3588 * This range is selected to be approximately centered on TCP_ISS / 2,
3589 * and easy to compute. We get this value by generating a 32-bit random
3590 * number, selecting out the high-order 17 bits, and then adding one so
3591 * that we never return zero.
3592 */
3593 int
3594 tcp_random(void)
3595 {
3596 int i;
3597
3598 mutex_enter(&tcp_random_lock);
3599 *tcp_random_fptr += *tcp_random_rptr;
3600
3601 /*
3602 * The high-order bits are more random than the low-order bits,
3603 * so we select out the high-order 17 bits and add one so that
3604 * we never return zero.
3605 */
3606 i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
3607 if (++tcp_random_fptr >= tcp_random_end_ptr) {
3608 tcp_random_fptr = tcp_random_state;
3609 ++tcp_random_rptr;
3610 } else if (++tcp_random_rptr >= tcp_random_end_ptr)
3611 tcp_random_rptr = tcp_random_state;
3612
3613 mutex_exit(&tcp_random_lock);
3614 return (i);
3615 }
3616
3617 /*
3618 * Split this function out so that if the secret changes, I'm okay.
3619 *
3620 * Initialize the tcp_iss_cookie and tcp_iss_key.
3621 */
3622
3623 #define PASSWD_SIZE 16 /* MUST be multiple of 4 */
3624
3625 void
3626 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
3627 {
3628 struct {
3629 int32_t current_time;
3630 uint32_t randnum;
3631 uint16_t pad;
3632 uint8_t ether[6];
3633 uint8_t passwd[PASSWD_SIZE];
3634 } tcp_iss_cookie;
3635 time_t t;
3636
3637 /*
3638 * Start with the current absolute time.
3639 */
3640 (void) drv_getparm(TIME, &t);
3641 tcp_iss_cookie.current_time = t;
3642
3643 /*
3644 * XXX - Need a more random number per RFC 1750, not this crap.
3645 * OTOH, if what follows is pretty random, then I'm in better shape.
3646 */
3647 tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
3648 tcp_iss_cookie.pad = 0x365c; /* Picked from HMAC pad values. */
3649
3650 /*
3651 * The cpu_type_info is pretty non-random. Ugggh. It does serve
3652 * as a good template.
3653 */
3654 bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
3655 min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
3656
3657 /*
3658 * The pass-phrase. Normally this is supplied by user-called NDD.
3659 */
3660 bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
3661
3662 /*
3663 * See 4010593 if this section becomes a problem again,
3664 * but the local ethernet address is useful here.
3665 */
3666 (void) localetheraddr(NULL,
3667 (struct ether_addr *)&tcp_iss_cookie.ether);
3668
3669 /*
3670 * Hash 'em all together. The MD5Final is called per-connection.
3671 */
3672 mutex_enter(&tcps->tcps_iss_key_lock);
3673 MD5Init(&tcps->tcps_iss_key);
3674 MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
3675 sizeof (tcp_iss_cookie));
3676 mutex_exit(&tcps->tcps_iss_key_lock);
3677 }
3678
3679 /*
3680 * Called by IP when IP is loaded into the kernel
3681 */
3682 void
3683 tcp_ddi_g_init(void)
3684 {
3685 tcp_timercache = kmem_cache_create("tcp_timercache",
3686 sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
3687 NULL, NULL, NULL, NULL, NULL, 0);
3688
3689 tcp_notsack_blk_cache = kmem_cache_create("tcp_notsack_blk_cache",
3690 sizeof (notsack_blk_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
3691
3692 mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
3693
3694 /* Initialize the random number generator */
3695 tcp_random_init();
3696
3697 /* A single callback independently of how many netstacks we have */
3698 ip_squeue_init(tcp_squeue_add);
3699
3700 tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
3701
3702 tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
3703
3704 /*
3705 * We want to be informed each time a stack is created or
3706 * destroyed in the kernel, so we can maintain the
3707 * set of tcp_stack_t's.
3708 */
3709 netstack_register(NS_TCP, tcp_stack_init, NULL, tcp_stack_fini);
3710 }
3711
3712
3713 #define INET_NAME "ip"
3714
3715 /*
3716 * Initialize the TCP stack instance.
3717 */
3718 static void *
3719 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
3720 {
3721 tcp_stack_t *tcps;
3722 int i;
3723 int error = 0;
3724 major_t major;
3725 size_t arrsz;
3726
3727 tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
3728 tcps->tcps_netstack = ns;
3729
3730 /* Initialize locks */
3731 mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
3732 mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
3733
3734 tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
3735 tcps->tcps_g_epriv_ports[0] = ULP_DEF_EPRIV_PORT1;
3736 tcps->tcps_g_epriv_ports[1] = ULP_DEF_EPRIV_PORT2;
3737 tcps->tcps_min_anonpriv_port = 512;
3738
3739 tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
3740 TCP_BIND_FANOUT_SIZE, KM_SLEEP);
3741 tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
3742 TCP_ACCEPTOR_FANOUT_SIZE, KM_SLEEP);
3743
3744 for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
3745 mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
3746 MUTEX_DEFAULT, NULL);
3747 }
3748
3749 for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
3750 mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
3751 MUTEX_DEFAULT, NULL);
3752 }
3753
3754 /* TCP's IPsec code calls the packet dropper. */
3755 ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
3756
3757 arrsz = tcp_propinfo_count * sizeof (mod_prop_info_t);
3758 tcps->tcps_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz,
3759 KM_SLEEP);
3760 bcopy(tcp_propinfo_tbl, tcps->tcps_propinfo_tbl, arrsz);
3761
3762 /*
3763 * Note: To really walk the device tree you need the devinfo
3764 * pointer to your device which is only available after probe/attach.
3765 * The following is safe only because it uses ddi_root_node()
3766 */
3767 tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
3768 tcp_opt_obj.odb_opt_arr_cnt);
3769
3770 /*
3771 * Initialize RFC 1948 secret values. This will probably be reset once
3772 * by the boot scripts.
3773 *
3774 * Use NULL name, as the name is caught by the new lockstats.
3775 *
3776 * Initialize with some random, non-guessable string, like the global
3777 * T_INFO_ACK.
3778 */
3779
3780 tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
3781 sizeof (tcp_g_t_info_ack), tcps);
3782
3783 tcps->tcps_kstat = tcp_kstat2_init(stackid);
3784 tcps->tcps_mibkp = tcp_kstat_init(stackid);
3785
3786 major = mod_name_to_major(INET_NAME);
3787 error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
3788 ASSERT(error == 0);
3789 tcps->tcps_ixa_cleanup_mp = allocb_wait(0, BPRI_MED, STR_NOSIG, NULL);
3790 ASSERT(tcps->tcps_ixa_cleanup_mp != NULL);
3791 cv_init(&tcps->tcps_ixa_cleanup_ready_cv, NULL, CV_DEFAULT, NULL);
3792 cv_init(&tcps->tcps_ixa_cleanup_done_cv, NULL, CV_DEFAULT, NULL);
3793 mutex_init(&tcps->tcps_ixa_cleanup_lock, NULL, MUTEX_DEFAULT, NULL);
3794
3795 mutex_init(&tcps->tcps_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
3796 tcps->tcps_reclaim = B_FALSE;
3797 tcps->tcps_reclaim_tid = 0;
3798 tcps->tcps_reclaim_period = tcps->tcps_rexmit_interval_max;
3799
3800 /*
3801 * ncpus is the current number of CPUs, which can be bigger than
3802 * boot_ncpus. But we don't want to use ncpus to allocate all the
3803 * tcp_stats_cpu_t at system boot up time since it will be 1. While
3804 * we handle adding CPU in tcp_cpu_update(), it will be slow if
3805 * there are many CPUs as we will be adding them 1 by 1.
3806 *
3807 * Note that tcps_sc_cnt never decreases and the tcps_sc[x] pointers
3808 * are not freed until the stack is going away. So there is no need
3809 * to grab a lock to access the per CPU tcps_sc[x] pointer.
3810 */
3811 mutex_enter(&cpu_lock);
3812 tcps->tcps_sc_cnt = MAX(ncpus, boot_ncpus);
3813 mutex_exit(&cpu_lock);
3814 tcps->tcps_sc = kmem_zalloc(max_ncpus * sizeof (tcp_stats_cpu_t *),
3815 KM_SLEEP);
3816 for (i = 0; i < tcps->tcps_sc_cnt; i++) {
3817 tcps->tcps_sc[i] = kmem_zalloc(sizeof (tcp_stats_cpu_t),
3818 KM_SLEEP);
3819 }
3820
3821 mutex_init(&tcps->tcps_listener_conf_lock, NULL, MUTEX_DEFAULT, NULL);
3822 list_create(&tcps->tcps_listener_conf, sizeof (tcp_listener_t),
3823 offsetof(tcp_listener_t, tl_link));
3824
3825 return (tcps);
3826 }
3827
3828 /*
3829 * Called when the IP module is about to be unloaded.
3830 */
3831 void
3832 tcp_ddi_g_destroy(void)
3833 {
3834 tcp_g_kstat_fini(tcp_g_kstat);
3835 tcp_g_kstat = NULL;
3836 bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
3837
3838 mutex_destroy(&tcp_random_lock);
3839
3840 kmem_cache_destroy(tcp_timercache);
3841 kmem_cache_destroy(tcp_notsack_blk_cache);
3842
3843 netstack_unregister(NS_TCP);
3844 }
3845
3846 /*
3847 * Free the TCP stack instance.
3848 */
3849 static void
3850 tcp_stack_fini(netstackid_t stackid, void *arg)
3851 {
3852 tcp_stack_t *tcps = (tcp_stack_t *)arg;
3853 int i;
3854
3855 freeb(tcps->tcps_ixa_cleanup_mp);
3856 tcps->tcps_ixa_cleanup_mp = NULL;
3857 cv_destroy(&tcps->tcps_ixa_cleanup_ready_cv);
3858 cv_destroy(&tcps->tcps_ixa_cleanup_done_cv);
3859 mutex_destroy(&tcps->tcps_ixa_cleanup_lock);
3860
3861 /*
3862 * Set tcps_reclaim to false tells tcp_reclaim_timer() not to restart
3863 * the timer.
3864 */
3865 mutex_enter(&tcps->tcps_reclaim_lock);
3866 tcps->tcps_reclaim = B_FALSE;
3867 mutex_exit(&tcps->tcps_reclaim_lock);
3868 if (tcps->tcps_reclaim_tid != 0)
3869 (void) untimeout(tcps->tcps_reclaim_tid);
3870 mutex_destroy(&tcps->tcps_reclaim_lock);
3871
3872 tcp_listener_conf_cleanup(tcps);
3873
3874 for (i = 0; i < tcps->tcps_sc_cnt; i++)
3875 kmem_free(tcps->tcps_sc[i], sizeof (tcp_stats_cpu_t));
3876 kmem_free(tcps->tcps_sc, max_ncpus * sizeof (tcp_stats_cpu_t *));
3877
3878 kmem_free(tcps->tcps_propinfo_tbl,
3879 tcp_propinfo_count * sizeof (mod_prop_info_t));
3880 tcps->tcps_propinfo_tbl = NULL;
3881
3882 for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
3883 ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
3884 mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
3885 }
3886
3887 for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
3888 ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
3889 mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
3890 }
3891
3892 kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
3893 tcps->tcps_bind_fanout = NULL;
3894
3895 kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) *
3896 TCP_ACCEPTOR_FANOUT_SIZE);
3897 tcps->tcps_acceptor_fanout = NULL;
3898
3899 mutex_destroy(&tcps->tcps_iss_key_lock);
3900 mutex_destroy(&tcps->tcps_epriv_port_lock);
3901
3902 ip_drop_unregister(&tcps->tcps_dropper);
3903
3904 tcp_kstat2_fini(stackid, tcps->tcps_kstat);
3905 tcps->tcps_kstat = NULL;
3906
3907 tcp_kstat_fini(stackid, tcps->tcps_mibkp);
3908 tcps->tcps_mibkp = NULL;
3909
3910 ldi_ident_release(tcps->tcps_ldi_ident);
3911 kmem_free(tcps, sizeof (*tcps));
3912 }
3913
3914 /*
3915 * Generate ISS, taking into account NDD changes may happen halfway through.
3916 * (If the iss is not zero, set it.)
3917 */
3918
3919 static void
3920 tcp_iss_init(tcp_t *tcp)
3921 {
3922 MD5_CTX context;
3923 struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
3924 uint32_t answer[4];
3925 tcp_stack_t *tcps = tcp->tcp_tcps;
3926 conn_t *connp = tcp->tcp_connp;
3927
3928 tcps->tcps_iss_incr_extra += (tcps->tcps_iss_incr >> 1);
3929 tcp->tcp_iss = tcps->tcps_iss_incr_extra;
3930 switch (tcps->tcps_strong_iss) {
3931 case 2:
3932 mutex_enter(&tcps->tcps_iss_key_lock);
3933 context = tcps->tcps_iss_key;
3934 mutex_exit(&tcps->tcps_iss_key_lock);
3935 arg.ports = connp->conn_ports;
3936 arg.src = connp->conn_laddr_v6;
3937 arg.dst = connp->conn_faddr_v6;
3938 MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
3939 MD5Final((uchar_t *)answer, &context);
3940 tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
3941 /*
3942 * Now that we've hashed into a unique per-connection sequence
3943 * space, add a random increment per strong_iss == 1. So I
3944 * guess we'll have to...
3945 */
3946 /* FALLTHRU */
3947 case 1:
3948 tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
3949 break;
3950 default:
3951 tcp->tcp_iss += (uint32_t)gethrestime_sec() *
3952 tcps->tcps_iss_incr;
3953 break;
3954 }
3955 tcp->tcp_valid_bits = TCP_ISS_VALID;
3956 tcp->tcp_fss = tcp->tcp_iss - 1;
3957 tcp->tcp_suna = tcp->tcp_iss;
3958 tcp->tcp_snxt = tcp->tcp_iss + 1;
3959 tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
3960 tcp->tcp_csuna = tcp->tcp_snxt;
3961 }
3962
3963 /*
3964 * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
3965 * on the specified backing STREAMS q. Note, the caller may make the
3966 * decision to call based on the tcp_t.tcp_flow_stopped value which
3967 * when check outside the q's lock is only an advisory check ...
3968 */
3969 void
3970 tcp_setqfull(tcp_t *tcp)
3971 {
3972 tcp_stack_t *tcps = tcp->tcp_tcps;
3973 conn_t *connp = tcp->tcp_connp;
3974
3975 if (tcp->tcp_closed)
3976 return;
3977
3978 conn_setqfull(connp, &tcp->tcp_flow_stopped);
3979 if (tcp->tcp_flow_stopped)
3980 TCP_STAT(tcps, tcp_flwctl_on);
3981 }
3982
3983 void
3984 tcp_clrqfull(tcp_t *tcp)
3985 {
3986 conn_t *connp = tcp->tcp_connp;
3987
3988 if (tcp->tcp_closed)
3989 return;
3990 conn_clrqfull(connp, &tcp->tcp_flow_stopped);
3991 }
3992
3993 static int
3994 tcp_squeue_switch(int val)
3995 {
3996 int rval = SQ_FILL;
3997
3998 switch (val) {
3999 case 1:
4000 rval = SQ_NODRAIN;
4001 break;
4002 case 2:
4003 rval = SQ_PROCESS;
4004 break;
4005 default:
4006 break;
4007 }
4008 return (rval);
4009 }
4010
4011 /*
4012 * This is called once for each squeue - globally for all stack
4013 * instances.
4014 */
4015 static void
4016 tcp_squeue_add(squeue_t *sqp)
4017 {
4018 tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
4019 sizeof (tcp_squeue_priv_t), KM_SLEEP);
4020
4021 *squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
4022 if (tcp_free_list_max_cnt == 0) {
4023 int tcp_ncpus = ((boot_max_ncpus == -1) ?
4024 max_ncpus : boot_max_ncpus);
4025
4026 /*
4027 * Limit number of entries to 1% of availble memory / tcp_ncpus
4028 */
4029 tcp_free_list_max_cnt = (freemem * PAGESIZE) /
4030 (tcp_ncpus * sizeof (tcp_t) * 100);
4031 }
4032 tcp_time_wait->tcp_free_list_cnt = 0;
4033 }
4034 /*
4035 * Return unix error is tli error is TSYSERR, otherwise return a negative
4036 * tli error.
4037 */
4038 int
4039 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
4040 boolean_t bind_to_req_port_only)
4041 {
4042 int error;
4043 tcp_t *tcp = connp->conn_tcp;
4044
4045 if (tcp->tcp_state >= TCPS_BOUND) {
4046 if (connp->conn_debug) {
4047 (void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
4048 "tcp_bind: bad state, %d", tcp->tcp_state);
4049 }
4050 return (-TOUTSTATE);
4051 }
4052
4053 error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
4054 if (error != 0)
4055 return (error);
4056
4057 ASSERT(tcp->tcp_state == TCPS_BOUND);
4058 tcp->tcp_conn_req_max = 0;
4059 return (0);
4060 }
4061
4062 /*
4063 * If the return value from this function is positive, it's a UNIX error.
4064 * Otherwise, if it's negative, then the absolute value is a TLI error.
4065 * the TPI routine tcp_tpi_connect() is a wrapper function for this.
4066 */
4067 int
4068 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
4069 cred_t *cr, pid_t pid)
4070 {
4071 tcp_t *tcp = connp->conn_tcp;
4072 sin_t *sin = (sin_t *)sa;
4073 sin6_t *sin6 = (sin6_t *)sa;
4074 ipaddr_t *dstaddrp;
4075 in_port_t dstport;
4076 uint_t srcid;
4077 int error;
4078 uint32_t mss;
4079 mblk_t *syn_mp;
4080 tcp_stack_t *tcps = tcp->tcp_tcps;
4081 int32_t oldstate;
4082 ip_xmit_attr_t *ixa = connp->conn_ixa;
4083
4084 oldstate = tcp->tcp_state;
4085
4086 switch (len) {
4087 default:
4088 /*
4089 * Should never happen
4090 */
4091 return (EINVAL);
4092
4093 case sizeof (sin_t):
4094 sin = (sin_t *)sa;
4095 if (sin->sin_port == 0) {
4096 return (-TBADADDR);
4097 }
4098 if (connp->conn_ipv6_v6only) {
4099 return (EAFNOSUPPORT);
4100 }
4101 break;
4102
4103 case sizeof (sin6_t):
4104 sin6 = (sin6_t *)sa;
4105 if (sin6->sin6_port == 0) {
4106 return (-TBADADDR);
4107 }
4108 break;
4109 }
4110 /*
4111 * If we're connecting to an IPv4-mapped IPv6 address, we need to
4112 * make sure that the conn_ipversion is IPV4_VERSION. We
4113 * need to this before we call tcp_bindi() so that the port lookup
4114 * code will look for ports in the correct port space (IPv4 and
4115 * IPv6 have separate port spaces).
4116 */
4117 if (connp->conn_family == AF_INET6 &&
4118 connp->conn_ipversion == IPV6_VERSION &&
4119 IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
4120 if (connp->conn_ipv6_v6only)
4121 return (EADDRNOTAVAIL);
4122
4123 connp->conn_ipversion = IPV4_VERSION;
4124 }
4125
4126 switch (tcp->tcp_state) {
4127 case TCPS_LISTEN:
4128 /*
4129 * Listening sockets are not allowed to issue connect().
4130 */
4131 if (IPCL_IS_NONSTR(connp))
4132 return (EOPNOTSUPP);
4133 /* FALLTHRU */
4134 case TCPS_IDLE:
4135 /*
4136 * We support quick connect, refer to comments in
4137 * tcp_connect_*()
4138 */
4139 /* FALLTHRU */
4140 case TCPS_BOUND:
4141 break;
4142 default:
4143 return (-TOUTSTATE);
4144 }
4145
4146 /*
4147 * We update our cred/cpid based on the caller of connect
4148 */
4149 if (connp->conn_cred != cr) {
4150 crhold(cr);
4151 crfree(connp->conn_cred);
4152 connp->conn_cred = cr;
4153 }
4154 connp->conn_cpid = pid;
4155
4156 /* Cache things in the ixa without any refhold */
4157 ASSERT(!(ixa->ixa_free_flags & IXA_FREE_CRED));
4158 ixa->ixa_cred = cr;
4159 ixa->ixa_cpid = pid;
4160 if (is_system_labeled()) {
4161 /* We need to restart with a label based on the cred */
4162 ip_xmit_attr_restore_tsl(ixa, ixa->ixa_cred);
4163 }
4164
4165 if (connp->conn_family == AF_INET6) {
4166 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
4167 error = tcp_connect_ipv6(tcp, &sin6->sin6_addr,
4168 sin6->sin6_port, sin6->sin6_flowinfo,
4169 sin6->__sin6_src_id, sin6->sin6_scope_id);
4170 } else {
4171 /*
4172 * Destination adress is mapped IPv6 address.
4173 * Source bound address should be unspecified or
4174 * IPv6 mapped address as well.
4175 */
4176 if (!IN6_IS_ADDR_UNSPECIFIED(
4177 &connp->conn_bound_addr_v6) &&
4178 !IN6_IS_ADDR_V4MAPPED(&connp->conn_bound_addr_v6)) {
4179 return (EADDRNOTAVAIL);
4180 }
4181 dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
4182 dstport = sin6->sin6_port;
4183 srcid = sin6->__sin6_src_id;
4184 error = tcp_connect_ipv4(tcp, dstaddrp, dstport,
4185 srcid);
4186 }
4187 } else {
4188 dstaddrp = &sin->sin_addr.s_addr;
4189 dstport = sin->sin_port;
4190 srcid = 0;
4191 error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid);
4192 }
4193
4194 if (error != 0)
4195 goto connect_failed;
4196
4197 CL_INET_CONNECT(connp, B_TRUE, error);
4198 if (error != 0)
4199 goto connect_failed;
4200
4201 /* connect succeeded */
4202 TCPS_BUMP_MIB(tcps, tcpActiveOpens);
4203 tcp->tcp_active_open = 1;
4204
4205 /*
4206 * tcp_set_destination() does not adjust for TCP/IP header length.
4207 */
4208 mss = tcp->tcp_mss - connp->conn_ht_iphc_len;
4209
4210 /*
4211 * Just make sure our rwnd is at least rcvbuf * MSS large, and round up
4212 * to the nearest MSS.
4213 *
4214 * We do the round up here because we need to get the interface MTU
4215 * first before we can do the round up.
4216 */
4217 tcp->tcp_rwnd = connp->conn_rcvbuf;
4218 tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
4219 tcps->tcps_recv_hiwat_minmss * mss);
4220 connp->conn_rcvbuf = tcp->tcp_rwnd;
4221 tcp_set_ws_value(tcp);
4222 tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
4223 if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
4224 tcp->tcp_snd_ws_ok = B_TRUE;
4225
4226 /*
4227 * Set tcp_snd_ts_ok to true
4228 * so that tcp_xmit_mp will
4229 * include the timestamp
4230 * option in the SYN segment.
4231 */
4232 if (tcps->tcps_tstamp_always ||
4233 (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
4234 tcp->tcp_snd_ts_ok = B_TRUE;
4235 }
4236
4237 /*
4238 * Note that tcp_snd_sack_ok can be set in tcp_set_destination() if
4239 * the SACK metric is set. So here we just check the per stack SACK
4240 * permitted param.
4241 */
4242 if (tcps->tcps_sack_permitted == 2) {
4243 ASSERT(tcp->tcp_num_sack_blk == 0);
4244 ASSERT(tcp->tcp_notsack_list == NULL);
4245 tcp->tcp_snd_sack_ok = B_TRUE;
4246 }
4247
4248 /*
4249 * Should we use ECN? Note that the current
4250 * default value (SunOS 5.9) of tcp_ecn_permitted
4251 * is 1. The reason for doing this is that there
4252 * are equipments out there that will drop ECN
4253 * enabled IP packets. Setting it to 1 avoids
4254 * compatibility problems.
4255 */
4256 if (tcps->tcps_ecn_permitted == 2)
4257 tcp->tcp_ecn_ok = B_TRUE;
4258
4259 /* Trace change from BOUND -> SYN_SENT here */
4260 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
4261 connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
4262 int32_t, TCPS_BOUND);
4263
4264 TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
4265 syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
4266 tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
4267 if (syn_mp != NULL) {
4268 /*
4269 * We must bump the generation before sending the syn
4270 * to ensure that we use the right generation in case
4271 * this thread issues a "connected" up call.
4272 */
4273 SOCK_CONNID_BUMP(tcp->tcp_connid);
4274 /*
4275 * DTrace sending the first SYN as a
4276 * tcp:::connect-request event.
4277 */
4278 DTRACE_TCP5(connect__request, mblk_t *, NULL,
4279 ip_xmit_attr_t *, connp->conn_ixa,
4280 void_ip_t *, syn_mp->b_rptr, tcp_t *, tcp,
4281 tcph_t *,
4282 &syn_mp->b_rptr[connp->conn_ixa->ixa_ip_hdr_length]);
4283 tcp_send_data(tcp, syn_mp);
4284 }
4285
4286 if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4287 tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4288 return (0);
4289
4290 connect_failed:
4291 connp->conn_faddr_v6 = ipv6_all_zeros;
4292 connp->conn_fport = 0;
4293 tcp->tcp_state = oldstate;
4294 if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4295 tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4296 return (error);
4297 }
4298
4299 int
4300 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
4301 int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
4302 {
4303 tcp_t *tcp = connp->conn_tcp;
4304 int error = 0;
4305 tcp_stack_t *tcps = tcp->tcp_tcps;
4306 int32_t oldstate;
4307
4308 /* All Solaris components should pass a cred for this operation. */
4309 ASSERT(cr != NULL);
4310
4311 if (tcp->tcp_state >= TCPS_BOUND) {
4312 if ((tcp->tcp_state == TCPS_BOUND ||
4313 tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
4314 /*
4315 * Handle listen() increasing backlog.
4316 * This is more "liberal" then what the TPI spec
4317 * requires but is needed to avoid a t_unbind
4318 * when handling listen() since the port number
4319 * might be "stolen" between the unbind and bind.
4320 */
4321 goto do_listen;
4322 }
4323 if (connp->conn_debug) {
4324 (void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
4325 "tcp_listen: bad state, %d", tcp->tcp_state);
4326 }
4327 return (-TOUTSTATE);
4328 } else {
4329 if (sa == NULL) {
4330 sin6_t addr;
4331 sin_t *sin;
4332 sin6_t *sin6;
4333
4334 ASSERT(IPCL_IS_NONSTR(connp));
4335 /* Do an implicit bind: Request for a generic port. */
4336 if (connp->conn_family == AF_INET) {
4337 len = sizeof (sin_t);
4338 sin = (sin_t *)&addr;
4339 *sin = sin_null;
4340 sin->sin_family = AF_INET;
4341 } else {
4342 ASSERT(connp->conn_family == AF_INET6);
4343 len = sizeof (sin6_t);
4344 sin6 = (sin6_t *)&addr;
4345 *sin6 = sin6_null;
4346 sin6->sin6_family = AF_INET6;
4347 }
4348 sa = (struct sockaddr *)&addr;
4349 }
4350
4351 error = tcp_bind_check(connp, sa, len, cr,
4352 bind_to_req_port_only);
4353 if (error)
4354 return (error);
4355 /* Fall through and do the fanout insertion */
4356 }
4357
4358 do_listen:
4359 ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
4360 tcp->tcp_conn_req_max = backlog;
4361 if (tcp->tcp_conn_req_max) {
4362 if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
4363 tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
4364 if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
4365 tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
4366 /*
4367 * If this is a listener, do not reset the eager list
4368 * and other stuffs. Note that we don't check if the
4369 * existing eager list meets the new tcp_conn_req_max
4370 * requirement.
4371 */
4372 if (tcp->tcp_state != TCPS_LISTEN) {
4373 tcp->tcp_state = TCPS_LISTEN;
4374 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
4375 connp->conn_ixa, void, NULL, tcp_t *, tcp,
4376 void, NULL, int32_t, TCPS_BOUND);
4377 /* Initialize the chain. Don't need the eager_lock */
4378 tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
4379 tcp->tcp_eager_next_drop_q0 = tcp;
4380 tcp->tcp_eager_prev_drop_q0 = tcp;
4381 tcp->tcp_second_ctimer_threshold =
4382 tcps->tcps_ip_abort_linterval;
4383 }
4384 }
4385
4386 /*
4387 * We need to make sure that the conn_recv is set to a non-null
4388 * value before we insert the conn into the classifier table.
4389 * This is to avoid a race with an incoming packet which does an
4390 * ipcl_classify().
4391 * We initially set it to tcp_input_listener_unbound to try to
4392 * pick a good squeue for the listener when the first SYN arrives.
4393 * tcp_input_listener_unbound sets it to tcp_input_listener on that
4394 * first SYN.
4395 */
4396 connp->conn_recv = tcp_input_listener_unbound;
4397
4398 /* Insert the listener in the classifier table */
4399 error = ip_laddr_fanout_insert(connp);
4400 if (error != 0) {
4401 /* Undo the bind - release the port number */
4402 oldstate = tcp->tcp_state;
4403 tcp->tcp_state = TCPS_IDLE;
4404 DTRACE_TCP6(state__change, void, NULL, ip_xmit_attr_t *,
4405 connp->conn_ixa, void, NULL, tcp_t *, tcp, void, NULL,
4406 int32_t, oldstate);
4407 connp->conn_bound_addr_v6 = ipv6_all_zeros;
4408
4409 connp->conn_laddr_v6 = ipv6_all_zeros;
4410 connp->conn_saddr_v6 = ipv6_all_zeros;
4411 connp->conn_ports = 0;
4412
4413 if (connp->conn_anon_port) {
4414 zone_t *zone;
4415
4416 zone = crgetzone(cr);
4417 connp->conn_anon_port = B_FALSE;
4418 (void) tsol_mlp_anon(zone, connp->conn_mlp_type,
4419 connp->conn_proto, connp->conn_lport, B_FALSE);
4420 }
4421 connp->conn_mlp_type = mlptSingle;
4422
4423 tcp_bind_hash_remove(tcp);
4424 return (error);
4425 } else {
4426 /*
4427 * If there is a connection limit, allocate and initialize
4428 * the counter struct. Note that since listen can be called
4429 * multiple times, the struct may have been allready allocated.
4430 */
4431 if (!list_is_empty(&tcps->tcps_listener_conf) &&
4432 tcp->tcp_listen_cnt == NULL) {
4433 tcp_listen_cnt_t *tlc;
4434 uint32_t ratio;
4435
4436 ratio = tcp_find_listener_conf(tcps,
4437 ntohs(connp->conn_lport));
4438 if (ratio != 0) {
4439 uint32_t mem_ratio, tot_buf;
4440
4441 tlc = kmem_alloc(sizeof (tcp_listen_cnt_t),
4442 KM_SLEEP);
4443 /*
4444 * Calculate the connection limit based on
4445 * the configured ratio and maxusers. Maxusers
4446 * are calculated based on memory size,
4447 * ~ 1 user per MB. Note that the conn_rcvbuf
4448 * and conn_sndbuf may change after a
4449 * connection is accepted. So what we have
4450 * is only an approximation.
4451 */
4452 if ((tot_buf = connp->conn_rcvbuf +
4453 connp->conn_sndbuf) < MB) {
4454 mem_ratio = MB / tot_buf;
4455 tlc->tlc_max = maxusers / ratio *
4456 mem_ratio;
4457 } else {
4458 mem_ratio = tot_buf / MB;
4459 tlc->tlc_max = maxusers / ratio /
4460 mem_ratio;
4461 }
4462 /* At least we should allow two connections! */
4463 if (tlc->tlc_max <= tcp_min_conn_listener)
4464 tlc->tlc_max = tcp_min_conn_listener;
4465 tlc->tlc_cnt = 1;
4466 tlc->tlc_drop = 0;
4467 tcp->tcp_listen_cnt = tlc;
4468 }
4469 }
4470 }
4471 return (error);
4472 }