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